我认为问题出在你身上
out = out + line
Cython没有定义运算符
+
对于C字符串。相反,它将它们转换为Python字符串,并连接这些字符串:
tmp1 = str(out)
tmp2 = str(line)
tmp3 = tmp1 + tmp2
out = get_c_string_from(tmp3)
out
因此,只要
tmp3
被摧毁(立即被摧毁)。
我会避免使用
strcat
not very efficient for repeated uses
. 而是跟踪当前字符串长度,并自己复制数据。假设您有一个未知的长度,您可能希望分配字符串
malloc
from libc.stdlib cimport free, malloc, realloc
from libc.string cimport memcpy
from cython import Py_ssize_t
cdef char *line
cdef Py_ssize_t i
cdef Py_ssize_t length = 0
cdef Py_ssize_t incrlength
cdef char *out = <char *>malloc(1) # Reallocate as needed
try:
out[0] = b'\x00' # keep C-strings null-terminated
for i in range(len(lines)):
line = lines[i]
incrlength = len(line)
out = <char *>realloc(out, length + incrlength + 1)
memcpy(out + length, line, incrlength)
length += incrlength
out[length] = '\x00' # keep C-strings null-terminated
return out # autoconversion back to a Python string
finally:
free(out)
这是我认为你应该做的事情的大致轮廓,并没有经过真正的测试。