Python中调用C++函数
2011-11-27 01:04
471 查看
Python开发效率高,运行效率低。而c/c++恰恰相反。因此在python脚本中调用c/c++的库,对python进行扩展,是很有必要的。使用python api,http://www.python.org/doc/ ,需要安装python-dev。
test.cpp文件如下
make:
g++ -shared -fpic test.cpp -o MyCppModule.so
test.py文件如下
/article/7626863.html
http://www.th7.cn/Program/Python/2011-07-07/29384.shtml
test.cpp文件如下
#include <python2.7/Python.h> //包含python的头文件 #include <string> #include <iostream> using namespace std; // 1 c/cpp中的函数 int my_c_function(const char* cmd,const char* opt) { string arg = string(cmd) + string(opt); cout << "arg:"<<arg<<endl; int n = system(arg.c_str()); return n; } // 2 python 包装 static PyObject * wrap_my_c_fun(PyObject *self, PyObject *args) { const char *cmd,*opt; int n; if (!PyArg_ParseTuple(args, "ss", &cmd,&opt))//这句是把python的变量args转换成c的变量command d return NULL; n = my_c_function(cmd,opt);//调用c的函数 return Py_BuildValue("i", n);//把c的返回值n转换成python的对象 } // 3 方法列表 static PyMethodDef MyCppMethods[] = { //MyCppFun1是python中注册的函数名,wrap_my_c_fun是函数指针 { "MyCppFun1", wrap_my_c_fun, METH_VARARGS, "Execute a shell command." }, { NULL, NULL, 0, NULL } }; // 4 模块初始化方法 PyMODINIT_FUNC initMyCppModule(void) { //初始模块,把MyCppMethods初始到MyCppModule中 PyObject *m = Py_InitModule("MyCppModule", MyCppMethods); if (m == NULL) return; }
make:
g++ -shared -fpic test.cpp -o MyCppModule.so
test.py文件如下
import MyCppModule r = MyCppModule.MyCppFun1("ls ","-l") print r
/article/7626863.html
http://www.th7.cn/Program/Python/2011-07-07/29384.shtml
相关文章推荐
- C++程序调用Python的函数(简单应用)及Ubuntu16.04下codeblocks的环境配置
- c++调用python函数
- C++调用 python 函数及返回值的处理【元组,字符串...】
- python 中调用c++定义的函数
- c++ 调用 python 函数中文返回值乱码
- C++调用Python函数
- 初始化函数中的虚函数调用( C++ vs python )
- Python调用C++函数(SWIG,VS2013使用numpy.i完成Numpy与C++数组转换)
- c++调用python函数接口
- C++与Python的混合编程-环境配置与调用无参函数
- C++调用python,直接调用模块内函数,调用类内函数
- c++调用python函数接口
- 导出 C++ 函数模块给 Python3 调用
- C++中调用python函数
- C++调用Python函数并传入传出参数
- c++调用python函数时,使用PyArray_SimpleNewFromData(nd, dims, typenum, data)函数时出现内存错误的问题
- python调用c++ 函数
- python嵌入C++------ boost.python如何在C++中调用含有不定长参数tuple变量和关键字参数dict变量的函数
- C++中调用python函数
- VS2008环境下C++调用Python模块函数----一封邮件引发的关机