我需要在 Windows 平台下从我的 C++ 项目中调用实现为 Python (3.6) 函数的管道。来自文件“ experiment_test.py ”的函数“ function_name ”将文本字符串作为输入参数,并返回另一个文本字符串作为结果。我尝试了下面的代码,但它不能正常工作 - 库shutil、codecs、makedirs等中的python 函数不起作用。
C++ 代码(减少):
std::string Text,Result;
PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;
Py_Initialize();
pName = PyUnicode_FromString("experiment_test");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "function_name");
pArgs = PyTuple_New(1);
pValue = PyUnicode_FromString(Text.c_str());
PyTuple_SetItem(pArgs, 0, pValue);
if (PyCallable_Check(pFunc))
{
pValue = PyObject_CallObject(pFunc, pArgs);
if (pValue != NULL)
{
Result = PyUnicode_AsUTF8(pValue);
Py_DECREF(pValue);
}
else return false;
}
// ...
Py_Finalize();
Run Code Online (Sandbox Code Playgroud)
Python代码(减少): …