I started off today wondering whether it is possible to save a python object for use in a C program, a proposition which, after many hours of reading looks naive. Here is a possible workaround:
1. Create a complex object dependent on many python libraries with data inside I need preserved.
2. Pickle the complex object and place it where it will be accessible.
3. Define compileme.py:
import pickle
thing = pickle.load(open('thing.pkl', 'r'))# an object with a method query(),
# which takes a numpy array as input
4. cython --embed -o compileme.c compileme.py
to generate a .c version of the script.
5. Define main.c:
#include <stdio.h>
#include//(A) something from compileme
int main(void) {
input = //(B) query takes a numpy array in python. Define something palatable.
double result = thing.query(input);
printf("%d", result);
}
6. Compile main.c properly, with all the right linkages.
It is not clear to me this basic solution strategy is sound, and I have a number of concerns:
- The
thing
is of a class from a library not even mentioned here, so itsquery()
method depends on that external python. How can I ensure the relevant parts are also being compiled and linked? - How should I include
compileme
in mymain.c
so thething
will be accessible there? (location (A) in the code) - How can I appropriately define an input to
thing
's method here? Do I need to use one of the many types defined incompileme.c
? (location (B) in the code) - How do I compile
main.c
with the proper linkages? - In doing all this, it appears I have to include references to the python header files from the
python-dev
package. Just to be clear, I am not actually including the interpreter by doing this, correct?
Here are some resources I've found during my search that prove it is possible to compile a simple python script to an executable compiled C program: Compile main Python program using Cython http://masnun.rocks/2016/10/01/creating-an-executable-file-using-cython/
Here is some relevant cython documentation: http://cython.readthedocs.io/en/latest/src/reference/compilation.html