Call Python from C++

前端 未结 2 435
一整个雨季
一整个雨季 2020-12-16 04:42

I\'m trying to call a function in a Python script from my main C++ program. The python function takes a string as the argument and returns nothing (ok.. \'None\'). It works

相关标签:
2条回答
  • 2020-12-16 05:28

    When you say "as long as the previous call is finished before the function is called again", I can only assume that you have multiple threads calling from C++ into Python. The python is not thread safe, so this is going to fail!

    Read up on the Global Interpreter Lock (GIL) in the Python manual. Perhaps the following links will help:

    • http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock
    • http://docs.python.org/c-api/init.html#PyEval_InitThreads
    • http://docs.python.org/c-api/init.html#PyEval_AcquireLock
    • http://docs.python.org/c-api/init.html#PyEval_ReleaseLock

    The GIL is mentioned on Wikipedia:

    • http://en.wikipedia.org/wiki/Global_Interpreter_Lock
    0 讨论(0)
  • 2020-12-16 05:29

    Thank you for your help!

    Yes you're right, there are several C threads. Never thought I'd need mutex for the interpreter itself - the GIL is a completly new concept for me (and isn't even once mentioned in the whole tutorial).

    After reading the reference (for sure not the easiest part of it, although the PyGILState_* functions simplify the whole thing a lot), I added an

    void initPython(){
        PyEval_InitThreads();
        Py_Initialize();
        PyEval_ReleaseLock();
    }
    

    function to initialise the interpreter correctly. Every thread creates its data structure, acquires the lock and releases it afterwards as shown in the reference.

    Works as it should, but when calling Py_Finalize() before terminating the process I get a segfault.. any problems with just leaving it?

    0 讨论(0)
提交回复
热议问题