VC与Python交互(四)(C执行Python文件)

extern "C" bool RunFyFuntion(char *strFilename, char *strModuleName, char *strFunctionName) { PyObject *pParams = NULL; PyObject *pModuleOld = NULL; PyObject *pModule =NULL; PyObject *pName = NULL; PyObject *pResult = NULL; PyObject *pDict = NULL; PyObject *pFunc = NULL; bool bResult = false; class PyThreadStateLock PyThreadLock; pName = PyString_FromString(strFilename); pModuleOld = PyImport_Import(pName); if(!pModuleOld) { QDLogs.SendMsg(LOG_OUTPUT_ERROR_TEAM, "%s file read error", strFilename); goto last; } pModule = PyImport_ReloadModule(pModuleOld); if(!pModule) { QDLogs.SendMsg(LOG_OUTPUT_ERROR_TEAM, "%s file read error", strFilename); goto last; } pDict = PyModule_GetDict(pModule); // 获得函数名 pFunc = PyDict_GetItemString(pDict, strFunctionName); if (!pFunc || !PyCallable_Check(pFunc)) { QDLogs.SendMsg(LOG_OUTPUT_ERROR_TEAM, "%s function read error", strFunctionName); goto last; } // 设置参数 pParams = PyTuple_New(2); PyTuple_SetItem(pParams, 0, Py_BuildValue("s", "abc")); PyTuple_SetItem(pParams, 1, Py_BuildValue("i", 1)); // 执行函数 pResult = PyObject_CallObject(pFunc, pParams); if(pResult == Py_True) { bResult = true; } else { QDLogs.SendMsg(LOG_OUTPUT_ERROR_TEAM, "%s function run error", strFunctionName); goto last; } last: Py_XDECREF(pFunc); Py_XDECREF(pDict); Py_XDECREF(pParams); Py_XDECREF(pModuleOld); Py_XDECREF(pModule); Py_XDECREF(pName); Py_XDECREF(pResult); return bResult; }

你可能感兴趣的:(VC与Python交互(四)(C执行Python文件))