What is the method for calling Python from C++?

In C++, calling Python methods typically requires using Python’s C API. Here is a simple example code:

#include <Python.h>

int main() {
    Py_Initialize();
    
    PyObject *pModule = PyImport_ImportModule("your_python_module_name");
    if (pModule) {
        PyObject *pFunc = PyObject_GetAttrString(pModule, "your_python_method_name");
        if (pFunc && PyCallable_Check(pFunc)) {
            PyObject *pArgs = PyTuple_New(0);
            PyObject *pValue = PyObject_CallObject(pFunc, pArgs);
            
            // 处理返回值
            if (pValue) {
                // do something with pValue
                Py_DECREF(pValue);
            } else {
                PyErr_Print();
            }
            
            Py_DECREF(pArgs);
            Py_DECREF(pFunc);
        } else {
            PyErr_Print();
        }
        
        Py_DECREF(pModule);
    } else {
        PyErr_Print();
    }
    
    Py_Finalize();
    
    return 0;
}

In this example, we start by initializing the Python interpreter, then import a specific Python module and retrieve its methods. We then create any necessary parameters for the methods, call the methods, and handle the return values. Finally, we clean up resources and shutdown the Python interpreter. It is important to ensure that the Python environment is correctly installed and configured.

bannerAds