小编Pav*_*vel的帖子

从 C++ 项目 (Visual Studio) 使用参数调用 Python 函数

我需要在 Windows 平台下从我的 C++ 项目中调用实现为 Python (3.6) 函数的管道。来自文件“ experiment_test.py ”的函数“ function_name ”将文本字符串作为输入参数,并返回另一个文本字符串作为结果。我尝试了下面的代码,但它不能正常工作 - 库shutilcodecsmakedirs等中的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代码(减少): …

c++ python

4
推荐指数
1
解决办法
3590
查看次数

标签 统计

c++ ×1

python ×1