I want to use a Python module within C++. In all examples I find (doc, SO1, SO2) they do things like Py_Initialize()
and Py_FinalizeEx()
, among other things, within the main
function. In my application, however, I am writing a small part of a larger system and have no access to main
. I am just writing a function that will be called many times somewhere in the program. What would be the way of doing all the initialization and finalization of the Python stuff in this case? I guess I could do everything within my function, but initializing the interpreter, importing, etc. every time the function is called will probably become very slow. I am not very experienced in C++, not sure if something like the following pseudocode is possible:
void my_func(void) {
if (my_func_is_called_for_the_first_time()) {
Py_Initialize();
module = load_python_module();
etc_related_to_init_stuff();
}
if (exiting_program()) { // Don't know how this would work, but you get the idea... Something like the `atexit` functionality from Python.
clean_everything_related_to_python_and_the_module();
Py_FinalizeEx();
}
// Actual code of my function using the package goes here...
}
Edit 1
Pseudocode:
#include <Python.h>
class MyPackage:
def constructor:
Py_Initialize();
self.module = load_python_module();
// Do other things related to the initialization here.
def destructor:
Py_FinalizeEx();
package = MyPackage(); // This is now global
void my_func(void) {
blah();
package.whatever();
}