0

I would like to embed numpy functions in C code and I have already managed to embed plain python functions that don't use external modules by using cython (and managed to put import numpy... at the top without actually using it), but when I use np.array in the function I run into a segfault on a line

__Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 6, __pyx_L1_error)

of the generated C source for that function. How can I make that work?

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;
}

Compilation steps:

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
Johannes Riecken
  • 2,301
  • 16
  • 17
  • 1
    Basically you need to initialize your module via `PyInit_foo` before it can be used. – ead Apr 01 '19 at 05:21
  • 1
    @ead I've proposed a different duplicate which I think is better because it is the same error rather than a generic "how do I call Cython from C" question. – DavidW Apr 01 '19 at 06:34

0 Answers0