我試圖嵌入用Cython代碼爲C以下O'reilly Cython book第8章我發現用Cython的documentation這一段,但還是不知道該怎麼辦:用Cython:分段故障使用API嵌入用Cython到C
If the C code wanting to use these functions is part of more than one shared library or executable, then import_modulename() function needs to be called in each of the shared libraries which use these functions. If you crash with a segmentation fault (SIGSEGV on linux) when calling into one of these api calls, this is likely an indication that the shared library which contains the api call which is generating the segmentation fault does not call the import_modulename() function before the api call which crashes.
我在OS X上運行的Python 3.4,用Cython 0.23和GCC 5的源代碼是transcendentals.pyx
和main.c
:
main.c
#include "transcendentals_api.h"
#include <math.h>
#include <stdio.h>
int main(int argc, char **argv)
{
Py_SetPythonHome(L"/Users/spacegoing/anaconda");
Py_Initialize();
import_transcendentals();
printf("pi**e: %f\n", pow(get_pi(), get_e()));
Py_Finalize();
return 0;
}
transcendentals.pyx
cdef api double get_pi():
return 3.1415926
cdef api double get_e():
print("calling get_e()")
return 2.718281828
我使用setup.py
和Makefile
編譯這些文件:
setup.py
:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
ext_modules=cythonize([
Extension("transcendentals", ["transcendentals.pyx"])
])
)
Makefile
python-config=/Users/spacegoing/anaconda/bin/python3-config
ldflags:=$(shell $(python-config) --ldflags)
cflags:=$(shell $(python-config) --cflags)
a.out: main.c transcendentals.so
gcc-5 $(cflags) $(ldflags) transcendentals.c main.c
transcendentals.so: setup.py transcendentals.pyx
python setup.py build_ext --inplace
cython transcendentals.pyx
clean:
rm -r a.out a.out.dSYM build transcendentals.[ch] transcendentals.so transcendentals_api.h
Howev呃,我來到錯誤Segmentation fault: 11
。任何想法可以幫助這個?謝謝!
如果你嘗試從python解釋器中導入超驗者,會發生什麼?在我的電腦上,導入錯誤:/tmp/q/transcendentals.so:undefined symbol:PyUnicodeUCS4_DecodeUTF8'。 'import_transcendentals()'在成功時返回'0',在失敗時返回'-1',即應該檢查返回值。 –