存储临时 Python 参考 Cython 的不安全 C 衍生品
虽然我很少有人问过类似的问题,但我无法解决如何解决。
基本上我有这个功能:
模块一.pyx:
cdef char *isInData(data, dataLength):
cdef char *ret = <char *>malloc(200)
memset(ret, 0x00, 200)
if (b"Hello" in data and b"World" in data):
strcat(ret, b"Hello World!")
return ret
模块二.pyx:
import one
from libc.stdlib cimport malloc,realloc, free
cdef char *tempo():
cdef char *str
str = one.isInData(b"Hello what is up World", 23)
# do some stuff
free(str)
问题发生在行 str = one.isInData("Hello What is up World", 23)
上,我假设尽快因为 isInData->ret
被分配给 str
。 isInData->ret
被删除导致此问题。但有人帮我解决这个问题吗?
Although I few similar questions already being asked, but I couldn't get head around on how to fix.
Basically I have this function:
Module one.pyx:
cdef char *isInData(data, dataLength):
cdef char *ret = <char *>malloc(200)
memset(ret, 0x00, 200)
if (b"Hello" in data and b"World" in data):
strcat(ret, b"Hello World!")
return ret
Module two.pyx:
import one
from libc.stdlib cimport malloc,realloc, free
cdef char *tempo():
cdef char *str
str = one.isInData(b"Hello what is up World", 23)
# do some stuff
free(str)
Issue occurs on line str = one.isInData("Hello what is up World", 23)
, I am assuming that as soon as isInData->ret
is assigned to str
. isInData->ret
is deleted which causes this issue. But annyone help me on how to fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此行执行 Python 导入
one
。它不知道one
中定义的任何cdef
函数(甚至不知道one
是 Cython 模块......)。因此,它假设 isInData 是一个可以查找的 Python 对象,并且它将是一个返回另一个 Python 对象的可调用对象。cdf char* str = some_python_function()
是不安全的,因为str
指向 Python 对象。然而,Python 对象只是一个临时对象,很可能几乎立即被释放。您的意思是:
它告诉 Cython 它是您正在导入的 Cython 模块,并且它应该期望在编译时找到声明。您可能需要编写 一个 pxd 文件 来提供声明。
我没有详细查看你的其余代码,所以不知道你是否正确处理了 C 字符串。但一般来说,您可能会发现使用 Python 字符串比使用 C 字符串处理更容易。
This line does a Python import of
one
. It doesn't know about anycdef
functions defined inone
(or even thatone
is a Cython module...). Therefore it assumes thatisInData
is a Python object that it can look up and that it'll be a callable returning another Python object.cdf char* str = some_python_function()
is unsafe becausestr
points into the Python object. However the Python object is only a temporary and is most likely freed almost immediately.What you mean is:
which tells Cython that it's a Cython module that you're importing, and it should expect to find the declarations at compile-time. You'll probably need to write a pxd file to give the declarations.
I haven't looked in detail at the rest of your code so don't know if you are handling C strings right. But in general you may find it easier just to use Python strings rather than messing around with C string handling.