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

2021-02-28 41点热度 1人点赞

首先本地需要安装有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;
        }
    }

未经允许不得转载!C++ 调用Python文件方法传递字典参数并接收返回值

本文地址:https://ai.52learn.online/10637

站长邮箱:ai52learn@foxmail.com