【发布时间】:2019-04-15 13:38:40
【问题描述】:
我正在尝试使用 Cython 和 ctypes 使用 Python 调用 c 库函数。
但是数据字节以某种方式损坏。有人可以帮忙找出问题吗?
testCRC.c:
#include <stdio.h>
unsigned char GetCalculatedCrc(const unsigned char* stream){
printf("Stream is %x %x %x %x %x %x %x\n",stream[0],stream[1],stream[2],stream[3],stream[4],stream[5],stream[6]);
unsigned char dummy=0;
return dummy;
}
wrapped.pyx:
# Exposes a c function to python
def c_GetCalculatedCrc(const unsigned char* stream):
return GetCalculatedCrc(stream)
test.py:
x_ba=(ctypes.c_ubyte *7)(*[0xD3,0xFF,0xF7,0x7F,0x00,0x00,0x41])
x_ca=(ctypes.c_char * len(x_ba)).from_buffer(x_ba)
y=c_GetCalculatedCrc(x_ca.value)
输出:
流是 d3 ff f7 7f 0 0 5f # 预期 0xD3,0xFF,0xF7,0x7F,0x00,0x00,0x41
解决方案:
1。 我必须将 cython 更新到 0.29 才能修复不允许使用类型化内存的错误。(只读问题)。
2。 它通过 x_ca.raw 工作。但是当 x_ca.value 被传递时,它会抛出错误“超出范围访问”。
根据@ead 和@DavidW 的建议:
'.pyx':
def c_GetCalculatedCrc(const unsigned char[:] stream):
# Exposes a c function to python
print "received %s\n" %stream[6]
return GetCalculatedCrc(&stream[0])
'test.py':
x_ba=(ctypes.c_ubyte *8)(*[0x47,0xD3,0xFF,0xF7,0x7F,0x00,0x00,0x41])
x_ca=(ctypes.c_char * len(x_ba)).from_buffer(x_ba)
y=c_GetCalculatedCrc(x_ca.raw)
输出:
流是 47 d3 ff f7 7f 0 0 41
【问题讨论】:
-
问题出在 ctypes 方面 - 试试
print(len(x_ca.value))