Why does the Python/C API crash on PyRun_SimpleFile?

后端 未结 7 753
一整个雨季
一整个雨季 2020-12-15 07:45

I\'ve been experimenting with embedding different scripting languages in a C++ application, currently I\'m trying Stackless Python 3.1. I\'ve tried several tutorials and exa

7条回答
  •  死守一世寂寞
    2020-12-15 08:22

    The below code will execute the test.py module. Python will search the module in the path set. So the path should be handled first.

    Py_Initialize();
    
    string path = "Python Scripts/";
    
    //Set the path
    PyRun_SimpleString("import sys");
    string str = "sys.path.append('" + path + "')";
    PyRun_SimpleString(str.c_str());
    
    //Dont use test.py as it actually searches sub module test>>py
    PyObject * moduleName = PyUnicode_FromString("test");
    PyObject * pluginModule = PyImport_Import(moduleName);
    
    if (pluginModule == nullptr)
    {
        PyErr_Print();
        return "";
    }
    
    //Do the executions here
    
    //clean up
    Py_DECREF(moduleName);
    Py_DECREF(pluginModule);
    Py_DECREF(transformFunc);
    Py_DECREF(result);
    
    Py_Finalize();
    

提交回复
热议问题