Call Python from C++

前端 未结 2 446
一整个雨季
一整个雨季 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: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?

提交回复
热议问题