この質問はthis oneに基づいていますが、ひねりがあります。私はcythonを使ってPython関数をコンパイルし、それをC言語で呼びたいと思っています。この単純なケースでは動作しますが、Pythonコードから別のPythonモジュールをインポートしようとすると動作しません。pythonでpythonファイルを呼び出し、Cからcythonを使ってimportする
world.pyx
def world():
return 10
hello.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
私は単にhello.pyx
にworld
機能を移動した場合には、それが正常に動作します。しかし、私はそれをインポートするときに書かれたように動作しません。
NameError: name 'hello' is not defined
Exception ignored in: 'hello.call_hello'
「世界の輸入世界から」ではないでしょうか? – ndim
また、 '--force'を使ってプログラムを実行しても何かがうまくいかなかった場合は、ここで強制されていることを調べることをお勧めします。 – ndim
私はあなたの問題の一部は、2つの異なる.pyxファイルを1つのモジュールにコンパイルしようとしていると思います。これはうまくいきません。各.pyxファイルは1つのモジュールに変換されます。 – DavidW