文章标题
2016-04-27 10:09
330 查看
C++调用Python脚本
#include <Python.h> class CPyCall { public: CPyCall() { Py_Initialize(); // 检查初始化是否成功 if (!Py_IsInitialized()) { MD_COMM_LOG_ERR(-1, "Py_Initialize Failed."); exit(0); } PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); MD_COMM_LOG_DEBUG("Py_Initialize Success."); } ~CPyCall() { std::map<std::string, PyObject*>::iterator iteModule = m_mapPyModule.begin(); while (iteModule != m_mapPyModule.end()) { m_mapPyModule.erase(iteModule++); } Py_Finalize(); MD_COMM_LOG_DEBUG("Py_Finalize Success."); } /* module: Python脚步的模块名 function: 要调用的函数名 format: 传递给Py_VaBuildValue函数的可变参数模板 返回值: 返回值需要使用原生的PyArg_Parse等函数解析支持 eg: PyCall( "pytest", "fun", "()" ); PyCall( "pytest", "fun1", "(i)", 12 ); PyCall( "pytest", "fun2", "(is)", 12, "12" ); */ PyObject* PyCall(const std::string& strModule, const std::string& strFunc, const char *format, ...) { PyObject* pFunc = NULL; PyObject* pParm = NULL; PyObject* pRetVal = NULL; if (ImportModule(strModule)) { MD_COMM_LOG_ERR(-1, "Add Python Module Failed."); return NULL; } std::map<std::string, PyObject*>::iterator iteModule = m_mapPyModule.end(); iteModule = m_mapPyModule.find(strModule); //查找函数 if (!(pFunc = PyObject_GetAttrString(iteModule->second, strFunc.c_str()))) { MD_COMM_LOG_ERR(-1, "Can't find function[%s] in module[%s]", strFunc.c_str(), strModule.c_str()); return NULL; } //创建参数 va_list vargs; va_start(vargs, format); pParm = Py_VaBuildValue(format, vargs); va_end(vargs); //函数调用 pRetVal = PyEval_CallObject(pFunc, pParm); Decref(pParm); Decref(pFunc); return pRetVal; } // 销毁对象 void Decref(PyObject* pObj) { if (pObj) { Py_DECREF(pObj); pObj = NULL; } } private: // 添加导入模块 int ImportModule(const std::string& strModule) { std::map<std::string, PyObject*>::iterator iteModule = m_mapPyModule.end(); iteModule = m_mapPyModule.find(strModule); if (iteModule == m_mapPyModule.end()) { PyObject* pMod = NULL; //导入模块 if (!(pMod = PyImport_ImportModule(strModule.c_str()))) { MD_COMM_LOG_ERR(-1, "Load module[%s] failed.", strModule.c_str()); return -1; } m_mapPyModule[strModule] = pMod; MD_COMM_LOG_DEBUG("Import new module[%s]", strModule.c_str()); } return 0; } private: std::map<std::string, PyObject*> m_mapPyModule; }; int main() { CPyCall oPy; // python文件名是当前目录下的文件,或者绝对路径(没测试) PyObject* pReto = Py.PyCall("python文件名", "函数名", "参数格式",(参数列表...)); // PyArg_Parse解析 return 0; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- 如何组织构建多文件 C 语言程序(二)
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- 关于指针的一些事情
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 如何写好 C main 函数