Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are a few things you need to do if you are invoking a Python function from a C/C++ callback. First when you save off your python function object, you need to increment the reference count with:</p> <pre><code>Py_INCREF(pFunc) </code></pre> <p>Otherwise Python has no idea you are holding onto an object reference, and it may garbage collect it, resulting in a segmentation fault when you try to use it from your callback.</p> <p>Then next thing you need to be concerned about is what thread is running when your C/C++ callback is invoked. If you are getting called back from another non-Python created thread (i.e. a C/C++ thread receiving data on a socket), then you <strong>MUST</strong> acquire Python's Global Interpreter Lock (GIL) before calling any Python API functions. Otherwise your program's behavior is undefined. To acquire the GIL you do:</p> <pre><code>void callback() { PyGILState_STATE gstate; gstate = PyGILState_Ensure(); // Get args, etc. // Call your Python function object PyObject * pInstance = PyObject_CallObject(pFunc, args); // Do any other needed Python API operations // Release the thread. No Python API allowed beyond this point. PyGILState_Release(gstate); } </code></pre> <p>Also, in your extension module's init function, you should do the following to ensure that threading is properly initialized:</p> <pre><code>// Make sure the GIL has been created since we need to acquire it in our // callback to safely call into the python application. if (! PyEval_ThreadsInitialized()) { PyEval_InitThreads(); } </code></pre> <p>Otherwise, crashes and strange behavior may ensue when you attempt to acquire the GIL from a non-Python thread.</p> <p>See <a href="http://docs.python.org/2/c-api/init.html#thread-state-and-the-global-interpreter-lock" rel="noreferrer">Non-Python Created Threads</a> for more detail on this.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload