Python 如何通过FFI传递Numpy PyArray*
其思想是能够修改库中的数组,就像函数的“输出”。 例如:Python 如何通过FFI传递Numpy PyArray*,python,numpy,python-cffi,Python,Numpy,Python Cffi,其思想是能够修改库中的数组,就像函数的“输出”。 例如: 您不能通过CFFI传递特定于CPython的PyXxx结构:您需要传递标准的C数据。通常我会回答,您需要使用标准C接口设计cdef()函数,例如: ffi.cdef(""" struct myimage_t { int width, height; float *data; }; int read_image(struct myimage_t *output); // fill i
您不能通过CFFI传递特定于CPython的
PyXxx
结构:您需要传递标准的C数据。通常我会回答,您需要使用标准C接口设计cdef()函数,例如:
ffi.cdef("""
struct myimage_t {
int width, height;
float *data;
};
int read_image(struct myimage_t *output); // fill in '*output'
void free_image(struct myimage_t *img); // free output->data
""")
myimage = ffi.new("struct myimage_t *")
if lib.read_image(myimage) < 0:
raise IOError
...
lib.free_image(myimage)
在example.py文件中:
from _example_cffi import ffi, lib
class Context:
pass
@ffi.def_extern()
def alloc_2d_numpy_array(handle, w, h):
context = ffi.from_handle(handle)
context.image = np.ndarray([w, h], dtype=np.float32)
return ffi.cast("float *", ffi.from_buffer(context.image))
context = Context()
lib.read_image(ffi.new_handle(context))
image = context.image
您不能通过CFFI传递特定于CPython的
PyXxx
结构:您需要传递标准的C数据。通常我会回答,您需要使用标准C接口设计cdef()函数,例如:
ffi.cdef("""
struct myimage_t {
int width, height;
float *data;
};
int read_image(struct myimage_t *output); // fill in '*output'
void free_image(struct myimage_t *img); // free output->data
""")
myimage = ffi.new("struct myimage_t *")
if lib.read_image(myimage) < 0:
raise IOError
...
lib.free_image(myimage)
在example.py文件中:
from _example_cffi import ffi, lib
class Context:
pass
@ffi.def_extern()
def alloc_2d_numpy_array(handle, w, h):
context = ffi.from_handle(handle)
context.image = np.ndarray([w, h], dtype=np.float32)
return ffi.cast("float *", ffi.from_buffer(context.image))
context = Context()
lib.read_image(ffi.new_handle(context))
image = context.image
很有趣,谢谢你的回复。很遗憾我们不能这样做。。。我们无法访问numpy的array C API。在torch中,我们可以使用FFI轻松地直接访问它们的矩阵对象,这非常有帮助。这就像是对您的x86可执行文件在ARM智能手机上不再工作感到悲哀。如果您有使用cpythoncapi操作PyObjects的代码,那么是的,它不能与cffi一起工作;这是cffi设计目标的一部分。我的回答举例说明了如何使用cffi的方法实现相同的结果——在需要访问某个Python对象时使用Python编写的回调。很有趣,感谢您的回答。很遗憾我们不能这样做。。。我们无法访问numpy的array C API。在torch中,我们可以使用FFI轻松地直接访问它们的矩阵对象,这非常有帮助。这就像是对您的x86可执行文件在ARM智能手机上不再工作感到悲哀。如果您有使用cpythoncapi操作PyObjects的代码,那么是的,它不能与cffi一起工作;这是cffi设计目标的一部分。我的答案给出了如何使用cffi的方法实现相同结果的示例——在需要访问某个Python对象时,使用Python编写的回调。