是否可以从字符串加载python函数,然后使用参数调用该函数并获取返回值?
我正在使用python C API从我的C++应用程序中运行python代码.我能够从文件中加载一个模块PyImport_Import,从中获取一个函数对象PyObject_GetAttrString,然后调用该函数PyObject_CallObject.我想做的是从字符串而不是文件加载模块/函数.是否有一些相当于PyImport_Import允许我传递一个字符串而不是文件?我需要将参数传递给我正在调用的函数,我需要访问返回值,所以我不能只使用PyRun_SimpleString.
在开启后我找到了这个解决方案PyRun_String.我正在创建一个新模块,获取它的字典对象,在调用时传递它以PyRun_String在我的新模块中定义一个函数,然后为新创建的函数获取一个函数对象并PyObject_CallObject通过我的args 调用它.这是我发现解决我的问题:
main.cpp
int main()
{
PyObject *pName, *pModule, *pArgs, *pValue, *pFunc;
PyObject *pGlobal = PyDict_New();
PyObject *pLocal;
//Create a new module object
PyObject *pNewMod = PyModule_New("mymod");
Py_Initialize();
PyModule_AddStringConstant(pNewMod, "__file__", "");
//Get the dictionary object from my module so I can pass this to PyRun_String
pLocal = PyModule_GetDict(pNewMod);
//Define my function in the newly created module
pValue = PyRun_String("def …Run Code Online (Sandbox Code Playgroud)