2

I am basically looking to see if it's possible to compile Python code into a C++ program such that a single binary is produced, then call the (compiled) python code as/with a function from within the C++ code.

Background: I have a C++ code that does some work and produces data that I want to plot. I then wrote a seperate Python script using SciPy that reads in the output data, processes it, and plots it to files. This all works as it is.

Basically, I am picturing:

void plotstuff() {
    my_python_func(); // This is the python script compiled into the c++ binary
}    

I don't need to pass anything between the python code and the C++ code other than being sure it's executed in the same directory. It may make things easier if I can pass string arguments, but again - not essential.

Can this be accomplished? Or is it generally a bad idea and I should just stick to having my C++ and python separate?

fergu
  • 329
  • 1
  • 5
  • 12
  • Look into the Python/C API reference: https://docs.python.org/2/c-api/ – Nick Beeuwsaert Jun 30 '15 at 18:04
  • What you are trying to do is called Embedding.that means that some parts of your application occasionally calls the **python** **interpreter** to run some Python code.although the application itself has nothing to do with python. – marc_s Jun 30 '15 at 18:35

2 Answers2

5

Yes: this is called embedding.

The best place to start is the official Python documentation on the topic. There's some sample code that shows how to call a Python function from C code.


Here's an extremely basic example, also from the Python docs:

#include <Python.h>

int
main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                     "print 'Today is',ctime(time())\n");
  Py_Finalize();
  return 0;
}
Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
  • This looks like what I want to use. Question though - when compiling everything, how can I include my python script inside the C++ executable (instead of in two seperate files)? Should I simply write another function which returns the python full script as a string, or is there a more elegant way (g++ -options)? – fergu Jun 30 '15 at 18:20
  • @kjfergu , to see how to embed an arbitrary file (for example, a Python script) into a C++ program, check out this question: http://stackoverflow.com/questions/4864866/c-c-with-gcc-statically-add-resource-files-to-executable-library – Robᵩ Jun 30 '15 at 18:24
0

Make a native extension (Python 2 or Python 3) out of your C++ code, and have your Python program import it. Then use py2exe or your favorite platform's counterpart to turn the Python program and your native extension into an executable.

Damian Yerrick
  • 4,602
  • 2
  • 26
  • 64