VC与Python交互(三)(自定义Python模块/函数)

1 首先定义一个函数,其中PyArg_ParseTuple来获得参数,si表示第一个是string,第二个是int

extern "C" static PyObject* SendStringInt(PyObject *pSelf, PyObject *pParams) { char* strMessage = 0; int nCount; if(!PyArg_ParseTuple(pParams, "si", &strMessage, &nCount)) { QDLogs.SendMsg(LOG_OUTPUT_ERROR_TEAM, "uable to parse parameter tuple"); return 0; } QDLogs.SendMsg(LOG_OUTPUT_ERROR_TEAM, strMessage); return (PyObject*)Py_None; }

2 做一个方法表,为自定义模块做准备,数组最后一个值要全为NULL

extern "C" PyMethodDef QDMethods [] = { {"sendStringInt", SendStringInt, METH_VARARGS, "SendStringInt" }, {NULL, NULL, NULL, NULL} };

3 注册模块

 void QdaoPythonManager::AddPythonModule(char* szModuleName, PyMethodDef* pDef) { class PyThreadStateLock PyThreadLock; if(!PyImport_AddModule(szModuleName)) { QDLogs.SendMsg(LOG_OUTPUT_ERROR_TEAM, "%s module could not be created", szModuleName); return; } // 将函数表加入这个模块 if(!Py_InitModule(szModuleName, pDef)) { QDLogs.SendMsg(LOG_OUTPUT_ERROR_TEAM, "%s API module could not be initialized", szModuleName); return; } return; } QdaoPythonManager::Instance().AddPythonModule("QD", QDMethods);

4 这样就可以在Python中调用了,在C中快速执行Python可以:

PyRun_SimpleString("import QD;QD.sendStringInt('哈哈', 1)");

你可能感兴趣的:(VC与Python交互(三)(自定义Python模块/函数))