How can I start a Python FROM C ++ stream?

Please note that I am not allowed to use Python 2.6. I have a Python 2.6 application that uses a multi-threaded C ++ API library created using boost-python. My option was to simply call the Python function callback from the C ++ enhancement stream, but despite many different attempts and exploring all the available online resources, I did not find any way to work. All proposed solutions revolve around a different combination of functions: Py_Initialize* , PyEval_InitThreads , PyGILState_Ensure , PyGILState_Release , but after trying all possible combinations, nothing works in practice, for example.

So this question is: how can I start and start a Python thread from C ++ ? I basically want to: create it, run it using the Python target function object, and forget about it.

Is it possible?

+5
source share
3 answers

Answer by OP How to call Python from boost stream? also responds to this OP or DP (Derived :)). It demonstrates how to start a thread from C ++ that accesses Python. I tested it and it works fine , although adaptation for pre-C ++ 11 is required. It uses Boost Python, it really is all 5 * answer and source code example here .

0
source

Based on the text below from your question:

Run Python thread from C ++? I basically want to: create it, run it using the Python target function object, and forget about it.

You might find it useful to just create a process using sytem :

 system("python myscript.py") 

And if you need to include arguments:

 string args = "arg1 arg2 arg3 ... argn" system("python myscript.py " + args) 
+1
source

You must call PyEval_InitThreads from your initialization (and leave the GIL saved). Then you can create pthread (using boost) and call PyGILState_Ensure in this thread, then call your python PyObject_CallFunction ( PyObject_CallFunction ?), Free any return value or handle any error ( PyErr_Print ?), Release the GIL with PyGILState_Release , and let the thread die .

 void *my_thread(void *arg) { PyGILState_STATE gstate; PyObject *result; gstate = PyGILState_Ensure(); if ((result = PyObject_CallFunction(func, NULL))) { Py_DECREF(result); } else { PyErr_Print(); } PyGILState_Release(gstate); return NULL; } 
0
source

Source: https://habr.com/ru/post/1261578/


All Articles