How to import Cython-generated module from python

2020-04-01 05:10发布

问题:


Want to improve this question? Add details and clarify the problem by editing this post.

Closed 2 years ago.

So I have a function written in python and I followed the steps in Cython Documentation 'Building a Cython module using distutils'. However, it's unclear to me how to use that module that's working in python (by import it) to be embedded in C/C++ ? I just want to compile a C/C++ code that imports a python generated module using Cython (I guess it's a 2 step process)

*To clarify, I have already done all the steps and created an python module from a .pyx source file. But my question is how to integrate that module into an existing C/C++ file.

回答1:

Just declare the stuff you want to call in c/c++ as cdef public

for example:

# cymod.pyx
from datetime import datetime

cdef public void print_time():
    print(datetime.now().ctime())

When cythonizing cymod.pyx to cymod.c, a cymod.h will be generated as well.

Then make a library, eg: cymod.lib (on windows).

In the c codes(main.c):

#include "Python.h"
#include "cymod.h"


int main(int argc, char **argv)
{
Py_Initialize();  

PyInit_cymod();  // in cymod.h
print_time();    // call the function from cython

Py_Finalize();
return 0;
}

Compile and run(main.exe)

Note: main.exe is highly bound to the python environments, one may run into errors such as cannot find pythonxx.dll, Fatal Python error: Py_Initialize: unable to load the file system codec. There are many solutions on this site.



回答2:

From looking at the Cython tutorial this is how Cython is used to extend Python with compiled C modules.

  1. Separate Cython module is written in Python. Cython will convert this to a static compiled module as if written in C.
  2. Use a setup.py file to compile Cython module as a *.so shared library. This shared library is actually a Python module.

    python setup.py build_ext --inplace

  3. From regular Python script import the Cython module

    import helloworld

Cython is normally used to extend Python with C. If on the other hand you want to embed Python code in your C program this is also possible. Taking a look at the official docs on embedding Python into C is a good place to read up on first.

Here is a github project explaining how to do that, and a blog on how to do that.