我想将numpy函数嵌入C代码中,并且我已经设法通过cython嵌入了不使用外部模块的普通python函数(并设法将import numpy...
放在顶部而不实际使用它) ),但是当我在函数中使用np.array
时,在一行上遇到段错误
__Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 6, __pyx_L1_error)
。我该怎么做?
foo.pyx:
# cython: language_level=3
import numpy as np
cimport numpy as np
cdef public int foo(int x):
return np.array(range(x)).max()
if __name__ == "__main__":
print(foo(5))
main.c:
#include <python3.7m/Python.h>
#include <stdio.h>
extern int foo(int);
int main() {
Py_Initialize();
printf("%d\n", foo(5));
return 0;
}
编译步骤:
cython --embed foo.pyx
gcc -g -o libfoo.so -fPIC -shared -pthread -I /usr/include/python3.7m foo.c -L /usr/lib/python3.7/config-3.7m-x86_64-linux-gnu/ -Xlinker --export-dynamic -I /usr/lib/python3.7/site-packages/numpy/core/include -lpython3.7
gcc -g main.c -L. -lfoo -lpython3.7