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