使用numpy的,我想創建從蟒蛇.so文件和C. 執行.so文件要做到這一點我以前用Cython轉換.pyx到是.so與用Cython
## print_me.pyx
cimport numpy as cnp
import numpy as np
cimport cython
cpdef public char* print_me(f):
# I know this numpy line does nothing
cdef cnp.ndarray[cnp.complex128_t, ndim=3] a = np.zeros((3,3,3), dtype=np.complex128)
return f
然後我用安裝的.py實際轉換.pyx到是.so
## setup.py
from distutils.core import setup
from Cython.Build import cythonize
import numpy as np
setup(
ext_modules=cythonize("print_me.pyx"),
include_dirs=[np.get_include()]
)
通過運行以下命令行,我能創造.so文件
python setup.py build_ext --inplace
當我嘗試使用以下C代碼運行此文件時,出現了分段錯誤。
/* toloadso.c */
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <time.h>
#include <python2.7/Python.h>
int main(void)
{
// define function
void *handle;
char* (*print_me)(PyObject*);
char *error;
PyObject* filename = PyString_FromString("hello");
// load so file
handle = dlopen("./print_me.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
dlerror();
// get function handler from so file
print_me = (char* (*)(PyObject*))dlsym(handle, "print_me");
// check if handler got error
error = dlerror();
if (error != NULL) {
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
// execute loaded function
printf("%s\n", (char*)(*print_me)(filename));
dlclose(handle);
exit(EXIT_SUCCESS);
}
我編譯如下命令這個.c文件:
gcc -fPIC -I/usr/include/ -o toloadso toloadso.c -lpython2.7 -ldl
(It compiled without error or warning)
當我試圖運行此代碼,我得到了一個分割故障
[[email protected] ~]# ./toloadso
Segmentation fault
如果我註釋掉以下line in print_me.pyx
cdef cnp.ndarray[cnp.complex128_t, ndim=3] a = np.zeros((3,3,3), dtype=np.complex128)
我的C代碼運行時沒有錯誤,但是一旦我取消註釋此行,它不起作用。 我認爲嘗試在cython中使用numpy會以某種方式產生錯誤。
我該如何解決? 非常感謝你的回覆
'print_me.so'是否作爲Python導入工作? – hpaulj
是的,它適用於python。但是當我通過加載調用函數時。所以從c文件中,它不起作用:( – jinki