【发布时间】:2017-08-16 16:40:16
【问题描述】:
这个问题是基于this one,但有一点不同。我想使用 cython 编译一个 python 函数,然后在 C 中调用它。在这个简单的情况下,它可以工作,但是当我尝试从我的 python 代码中导入另一个 python 模块时,它就不起作用了。
世界.pyx
def world():
return 10
你好.pyx
import world
def hello():
ret = 5 + world()
return ret
cdef public int call_hello():
return hello()
main.c
#include <Python.h>
#include "hello.h"
int main() {
Py_Initialize();
PyInit_hello();
int v = call_hello();
printf("the value is %d\n",v);
Py_Finalize();
return 0;
}
cython -3 --force world.pyx hello.pyx
clang -c world.c hello.c main.c -I/Users/aneben/.pyenv/versions/3.6.1/Python.framework/Versions/3.6/include/python3.6m -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
clang -L/Users/aneben/.pyenv/versions/3.6.1/Python.framework/Versions/3.6/lib/python3.6/config-3.6m-darwin -lpython3.6m -ldl -framework CoreFoundation world.o hello.o main.o -o main
如果我只是将world 函数移动到hello.pyx,那么它工作正常。但是当我导入它时它并没有像写的那样工作。
./main
NameError: name 'hello' is not defined
Exception ignored in: 'hello.call_hello'
【问题讨论】:
-
不应该是
from world import world吗? -
另外,如果我使用
--force运行程序时出现问题,最好看看这里强制执行的操作。 -
我认为您的部分问题是您试图将两个不同的 .pyx 文件编译到一个模块中,但这是行不通的。每个 .pyx 文件都转换为一个模块。