0

I have a python program (possiblly with cython extensions) made up of a main program and one or more support modules.

I know it is possible to build each module into it's own so and the main program into an executable using cython

However what I would like to do is build the program and it's support modules into a single executable. Is that possible with cython on Linux?

plugwash
  • 9,724
  • 2
  • 38
  • 51

1 Answers1

1

Yes it's possible, but a little hackery is required.

First lets consider our main program and a support library

cythontest.pyx:

cpdef int square(int n):
return n * n

cythontestmain.pyx

import cythontest
print(cythontest.square(100))

Lets build it with:

cython3 --embed cythontestmain.pyx
cython3 cythontest.pyx
gcc -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python3.5m -o cythontestmain cythontestmain.c cythontest.c -lpython3.5m

Unfortunately this doesn't work. The loader can't find the module. Fortunately it is possible to load it manually by adding a couple of lines to the top of cythontestmain.pyx

cdef extern void * PyInit_cythontest()
PyInit_cythontest()

(the return type of void * is not strictly correct, but since we are throwing away the return value anyway it's unlikely to be an issue in practice).

We can now build and run the program successfully.

plugwash
  • 9,724
  • 2
  • 38
  • 51
  • 1
    you should declare it as `cdef extern object PyInit_cythontest()`, then Cython will automaticly check and handle possible errors. – ead Apr 06 '19 at 10:54