Calling Cython function from C code raises segmentation fault

后端 未结 2 958
耶瑟儿~
耶瑟儿~ 2020-11-29 12:49

I\'m trying to call cython (cdef) function in C program. When the cdef function contains python statements, e.g. print(0.5), or python (def) functions, calling the (cdef) fu

2条回答
  •  死守一世寂寞
    2020-11-29 13:10

    I guess you are using Cython 0.29. Since 0.29, PEP-489 multi-phase module initialisation has been enabled for Python versions >=3.5. This means, using PyInit_XXX is no longer sufficient, as you are experiencing.

    Cython's documentation suggest to use inittab mechanism, i.e. your main-function should look something like:

    #include "Python.h"
    #include "transcendentals.h"
    #include 
    #include 
    
    int main(int argc, char **argv) {
      int status=PyImport_AppendInittab("transcendentals", PyInit_transcendentals);
      if(status==-1){
        return -1;//error
      } 
      Py_Initialize();
      PyObject *module = PyImport_ImportModule("transcendentals");
    
      if(module==NULL){
         Py_Finalize();
         return -1;//error
      }
    
      printf("pi**e: %f\n", pow(PI, get_e()));
      Py_Finalize();
      return 0;
    }
    

    Another possibility to restore the old behavior would be to define macro CYTHON_PEP489_MULTI_PHASE_INIT=0 and thus overriding the default by e.g. passing -DCYTHON_PEP489_MULTI_PHASE_INIT=0 to gcc on the command line.

提交回复
热议问题