如何使用cython将C char数组读入python字节数组中? [英] How do I read a C char array into a python bytearray with cython?
问题描述
我有一个带有字节及其大小的数组:
I have an array with bytes and its size:
cdef char *bp
cdef size_t size
如何将数组读入Python字节数组(或其他易于腌制的适当结构)? / p>
How do I read the array into a Python bytearray (or another appropriate structure that can easily be pickled)?
推荐答案
三种相当简单的方法:
-
使用我在注释中建议的适当的C API函数:
Use the appropriate C API function as I suggested in the comments:
from cpython.bytes cimport PyBytes_FromStringAndSize
output = PyBytes_FromStringAndSize(bp,size)
对于足够大的字符串,这可能是一个问题。对于Python 2,函数的命名方式类似,但是使用 PyString
而不是 PyBytes
。
This makes a copy, which may be an issue with a sufficiently large string. For Python 2 the functions are similarly named but with PyString
rather than PyBytes
.
使用键入的memoryview查看char指针,从中获取一个numpy数组:
View the char pointer with a typed memoryview, get a numpy array from that:
cdef char[::1] mview = <char[:size:1]>(bp)
output = np.asarray(mview)
这不应该制作副本,因此如果大的话可能会更有效。
This shouldn't make a copy, so could be more efficient if large.
执行副本手动:
output = bytearray(size)
for i in range(size):
output[i] = bp[i]
(如果需要,可以用Cython加速)
(this could be somewhat accelerated with Cython if needed)
我认为您遇到的是ctypes(基于后续您在评论中链接到的问题)是您无法将C指针传递给ctypes Python接口。如果您尝试将 char *
传递给Python函数,Cython将尝试将其转换为字符串。之所以失败,是因为它在第一个0元素处停止(因此需要大小)。因此,您没有向ctypes传递 char *
,而是向它传递了一个无意义的Python字符串。
This issue I think you're having with ctypes (based on the subsequent question you linked to in the comments) is that you cannot pass C pointer to the ctypes Python interface. If you try to pass a char*
to a Python function Cython will try to convert it to a string. This fails because it stops at the first 0 element (hence you need size). Therefore you aren't passing ctypes a char*
, you're passing it a nonsense Python string.
这篇关于如何使用cython将C char数组读入python字节数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!