我是Cython的新手,只是尝试尝试一个简单的脚本。我无法从模块中导入函数并在另一个文件中使用它,但是如果我在同一文件中声明该函数,则效果很好。这可能是问题所在。我想念什么吗?
这是原始代码段(test_cy.pyx):
# test_cy.pyx
import json
cpdef char* say_hello():
message = json.dumps({"message": "Hello world"})
return message.encode()
cdef char* fn(int n):
cdef char* hello = say_hello()
return hello
def test():
cdef char* n = fn(1000)
print(n)
我可以这样运行(编译后):
>>> import test_cy
>>> test_cy.test()
b'Hello world'
但是,如果我将say_hello函数移到另一个文件(utils.pyx):
# utils.pyx
import json
cpdef char* say_hello():
message = json.dumps({"message": "Hello world"})
return message.encode()
...并将其导入我的原始test_cy.pyx文件中,如下所示:
# test_cy.pyx
from utils import say_hello
cdef char* fn(int n):
cdef char* hello = say_hello()
return hello
def test():
cdef char* n = fn(1000)
print(n)
我收到以下错误,无法编译它:
>>> python3 setup.py build_ext --inplace
...
Error compiling Cython file:
------------------------------------------------------------
...
from utils import say_hello
cdef char* fn(int n):
cdef char* hello = say_hello()
^
------------------------------------------------------------
test_cy.pyx:4:7: Storing unsafe C derivative of temporary Python reference
Traceback (most recent call last):
File "setup.py", line 11, in <module>
sources=["utils.pyx"]
File "/Users/asim/.pyenv/versions/3.6.9/lib/python3.6/site-packages/Cython/Build/Dependencies.py", line 1101, in cythonize
cythonize_one(*args)
File "/Users/asim/.pyenv/versions/3.6.9/lib/python3.6/site-packages/Cython/Build/Dependencies.py", line 1224, in cythonize_one
raise CompileError(None, pyx_file)
Cython.Compiler.Errors.CompileError: test_cy.pyx
这是我的setup.py文件:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
ext_modules = cythonize([
Extension("test_cy",
sources=["test_cy.pyx"]
),
Extension("utils",
sources=["utils.pyx"]
)
])
)
请帮助我,因为它很简单,例如从另一个模块导入函数,应该不会那么复杂。我可能缺少一些琐碎的东西。谢谢!
cpdef char* say_hello():
message = json.dumps({"message": "Hello world"})
return message.encode()
这是一场等待发生的灾难(尽管Cython似乎无法发出警告)。您char*
指向的数据由message.encode()
-临时Python对象的结果保存,该对象在创建后即被销毁。因此,您char*
立即无效。
考虑一下用C表示的话:要返回char*
某人,必须拥有,char*
并且您应该确切知道该所有者是谁。没有一种简单,明智的方法来返回a,char*
而无需负责分配/取消分配您自己。除非您准备这样做并了解如何做,否则我建议您char*
从代码中删除所有代码,然后返回Python对象。
您收到的错误特别是因为Cython用来cimport
了解Cython函数。
from utils cimport say_hello
没有cimport
它,相信这say_hello
只是返回普通Python对象的普通Python函数。但是,即使进行了此更改,您的代码仍然无效-您已将错误移到了Cython无法看到的地方。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句