3

I am trying to embed a piece of Cython code in a C++ project, such that I can compile a binary that has no dependencies on Python 2.7 (so users can run the executable without having Python installed). The Cython source is not pure Cython: There is also Python code in there.

I am compiling my Cython code using distutils in the following script (setup.py):

from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("test.pyx")
)

I then run the script using python setup.py build_ext --inplace. This generates a couple of files: test.c, test.h, test.pyd and some library files: test.exp, test.obj and test.lib.

What would be the proper procedure to import this into C++? I managed to get it working by including test.c and test.h during compilation and test.lib during linking.

I am then able to call the Cython functions after I issue

Py_Initialize();
inittest();

in my C++ code.

The issue is that there a numerous dependencies on Python, both during compilation (e.g., in test.h) as well in during linking. Bottom-line is that in order to run the executable, Python has to be installed (otherwise I get errors on missing python27.dll).

Am I going in the right direction with this approach? There are so many options that I am just very confused on how to proceed. Conceptually, it also does not make sense why I should call Py_Initialize() if I want the whole thing to be Python-independent. Furthermore, this is apparently the `Very High Level Embedding' method instead a low-level Cython embedding, but this is just how I got it to work.

If anybody has any insights on this, that would be really appreciated.

sfjac
  • 7,119
  • 5
  • 45
  • 69
pansen
  • 117
  • 1
  • 8

2 Answers2

2

Cython cannot make Python code Python-independent; it calls into the Python library in order to handle Python types and function calls. If you want your program to be Python-independent then you should not write any Python code.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

(This is primarily extra detail to Ignacio Vazquez-Abrams's answer which says that you can't eliminate the Python dependency)

If you don't want to force your users to have Python installed themselves, you could always bundle python27.dll with your application (read the license agreement, but I'm almost certain it's fine!).

However, as soon as you do an import in your code, you either have to bundle the relevant module, or make sure it (and anything it imports!) is compiled with Cython. Unless you're doing something very trivial then you could end spending a lot of time chasing dependencies. This includes the majority of the standard library.

Community
  • 1
  • 1
DavidW
  • 29,336
  • 6
  • 55
  • 86