zoukankan      html  css  js  c++  java
  • C++ 调用Python文件方法传递字典参数并接收返回值

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

  • 相关阅读:
    Lucene
    coreseek
    Sphinx学习之sphinx的安装篇
    在Hive中使用Avro
    Hive中实现group concat功能(不用udf)
    Fresnel Reflection
    安装Windows更新程序遇到错误:0x80070422
    float4与half4数据类型
    Dijkstra算法(三)之 Java详解
    地图四叉树一般用在GIS中,在游戏寻路中2D游戏中一般用2维数组就够了
  • 原文地址:https://www.cnblogs.com/wjshan0808/p/8409674.html
Copyright © 2011-2022 走看看