使用 CFFI 的缓冲协议

Buffer protocol using CFFI

我想公开对象的缓冲协议,就像 in this example of the Cython documentation, however I need to do this using CFFI 一样,但我找不到任何公开缓冲协议的示例。

我对这个问题的理解是,您有一些从 CFFI 接口获得的数据,并希望使用标准 Python 缓冲协议(许多 C 扩展使用该协议来快速访问)来公开它数组数据)。

好消息 ffi.buffer() 命令(说实话,直到 OP 提到它我才知道!)公开了 Python 接口和 C-API侧缓冲协议。不过,它仅限于将数据查看为无符号 char/byte 数组。幸运的是,使用其他 Python 对象(例如 memoryview 可以将其视为其他类型)。

post 的其余部分是一个示例:

# buf_test.pyx
# This is just using Cython to define a couple of functions that expect
# objects with the buffer protocol of different types, as an easy way
# to prove it works. Cython isn't needed to use ffi.buffer()!
def test_uchar(unsigned char[:] contents):
    print(contents.shape[0])
    for i in range(contents.shape[0]):
        contents[i]=b'a'

def test_double(double[:] contents):
    print(contents.shape[0])
    for i in range(contents.shape[0]):
        contents[i]=1.0

...和 ​​Python 文件使用 cffi

import cffi
ffi = cffi.FFI()

data = ffi.buffer(ffi.new("double[20]")) # allocate some space to store data
         # alternatively, this could have been returned by a function wrapped
         # using ffi

# now use the Cython file to test the buffer interface
import pyximport; pyximport.install()
import buf_test

# next line DOESN'T WORK - complains about the data type of the buffer
# buf_test.test_double(obj.data) 

buf_test.test_uchar(obj.data) # works fine - but interprets as unsigned char

# we can also use casts and the Python
# standard memoryview object to get it as a double array
buf_test.test_double(memoryview(obj.data).cast('d'))