1

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.

Zhenlin Jin
  • 19
  • 1
  • 3

2 Answers2

2

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.

oz1
  • 938
  • 7
  • 18
1

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.

MrJLP
  • 978
  • 6
  • 14
  • I have done all the steps above. My question is how to integrate that module(in your case helloworld) into a current existing C/C++ file. I would like to use that function. Thanks for the comments though! – Zhenlin Jin May 09 '17 at 18:54
  • Ok. I added some links on how to embed Python into C. I think the regular use for Cython is to extend Python with C though – MrJLP May 09 '17 at 19:34