-1

我想为一个对象公开一个缓冲区协议,就像在 Cython 文档的这个示例中一样,但是我需要使用CFFI来执行此操作,并且我无法找到任何示例来公开缓冲区协议。

4

1 回答 1

3

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

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

该帖子的其余部分是一个说明性示例:

# 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

...以及使用 cffi 的 Python 文件

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'))
于 2015-10-01T06:54:40.410 回答