-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 に答える