您的位置:首页 > 编程语言 > C语言/C++

C++ 调用Python文件方法传递字典参数并接收返回值

2018-02-03 15:48 936 查看
首先本地需要安装有Python环境,然后在c++工程中包含Python的头文件,引用Python的lib库。

//python 初始化
Py_Initialize();
if (!Py_IsInitialized())
{
return;
}
//运行脚本导入环境变量
PyRun_SimpleString("import sys");
PyRun_SimpleString("import os");
PyRun_SimpleString("import string");
//py文件的存放位置
string strPyPath = string("sys.path.append('") + m_strPyLocation + string("')");
PyRun_SimpleString(strPyPath.c_str());
//载入py脚本
PyObject* pModule = PyImport_ImportModule("pyscript");// PyImport_Import(pName);
if (!pModule)
{
return;
}
//获取py方法
PyObject* pFunc = PyObject_GetAttrString(pModule, "OnFunc"); //PyDict_GetItemString(pDict, "pyscript");
if (!pFunc || !PyCallable_Check(pFunc))
{
return;
}
//构建py方法字典参数
PyObject *pArgsT = PyTuple_New(1);
PyObject* pArgsD = PyDict_New();
PyDict_SetItemString(pArgsD, "key", Py_BuildValue("s", "value"));
PyTuple_SetItem(pArgsT, 0, pArgsD);
//调用py方法
PyObject *pReturn = PyEval_CallObject(pFunc, pArgsT);//PyObject_CallObject(pFunc, pArgs);
if (pReturn == NULL)
{
return;
}
//获取py返回值
PyArg_Parse(pReturn, "s", &szBuffer);//char szBuffer[256] = {0};
//clear
Py_DECREF(pName);
Py_DECREF(pDict);
Py_DECREF(pModule);
Py_DECREF(pFunc);
Py_DECREF(pArgsT);
Py_DECREF(pArgsD);
Py_DECREF(pReturn);
Py_Finalize();


pyscript.py脚本示例

def OnFunc(params):
ret=''
ret+=params["key"]
return ret


附加 返回值 Tuple-List 解析

//调用py方法
PyObject *pReturnTuple =PyObject_CallObject(pFunc, pArgsT0); //PyEval_CallObject(pFunc, pArgsT0);
if (pReturnTuple == NULL)
return 0;

int nTupleSize = PyTuple_Size(pReturnTuple);
for (int l = 0; l < nTupleSize; l++)
{
PyObject *pTupleList = PyTuple_GetItem(pReturnTuple, l);
int nTupleListSize = PyList_Size(pTupleList);
for (int m = 0; m < nTupleListSize; m++)
{
PyObject* pTupleListValue = PyList_GetItem(pTupleList, m);
int nValue = 0;
PyArg_Parse(pTupleListValue, "i", &nValue);
std::cout << nValue << std::endl;
}
}


在线文档 https://docs.python.org/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐