我尝试在cython cdef块中调用回调函数,我可以在cython函数调用期间打印实际数据,但是当我的回调函数被调用或我在cython cdef块中调用print(buffer)时,我得到了带有b''的(参数/结果),我尝试其他演示,一切正常。
视窗 10, Python3.7, Cython
cython block
cdef ikcp_output(self, char *buffer, int size):
print("size: {}".format(size)) this can work
for i in range(size):
print(buffer[i]) # this can also works
cdef char* o
o = <char*> malloc(sizeof(char) * size)
memcpy(o, buffer, size)
for i in range(size):
print(o[i]) # this can also works
print(o) # this output b''
self.output(o) # the callback function get a parameter b''
free(o)
start iter buffer
0
0
0
1
81
0
0
32
28
-50
-113
-50
0
0
0
0
0
0
0
0
49
50
49
51
50
49
51
49
51
49
50
10
start iter o
0
0
0
1
81
0
0
32
28
-50
-113
-50
0
0
0
0
0
0
0
0
49
50
49
51
50
49
51
49
51
49
50
10
32
b'' # this is what i got in callback function
client output
output data b'' to addr: ('127.0.0.1', 8888)
调用print(o)
或self.func(o)
涉及将o
转换为Python对象,在本例中为bytes
对象。此转换假设char*
是 c 字符串(即以 null 结尾),因为 Cython 没有其他方法来确定长度。但是,缓冲区以 0 开头,因此读取长度为 0 的字符串。
正确的解决方案是使用PyBytes_FromStringAndSize
手动进行转换。你传递一个char*
和字符串的长度(因此它不假设第一个 0 是字符串的末尾)。您可以从cpython.bytes
cimport
它。