您PyXxx
不能通过 CFFI 传递特定于 CPython 的结构:您需要传递标准 C 数据。通常我会回答你需要使用标准 C 接口设计你的 cdef()'ed 函数,例如:
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)
然后,您需要手动将其转换myimage
为 numpy 数组,位于上面的“...”代码中。
一种更好的选择是使用 Python 回调:根据规范创建 numpy 数组并返回 C 标准float *
指针的回调。numpy 数组本身保存在回调的某个位置。您可以将其保存为 Python 全局,或者更干净地使用通过 C 传递的“句柄”。需要 API 版本,而不是 ABI。在 _example_build.py 中:
ffi.cdef("""
extern "Python" float *alloc_2d_numpy_array(void *handle, int w, int h);
void read_image(void *handle);
""")
ffi.set_source("_example_cffi", """
void read_image(void *handle)
{
// the C code that eventually invokes
float *p = alloc_2d_numpy_array(handle, w, h);
// and then fill the data at 'p'
}
""")
ffi.compile(verbose=True)
在文件 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