现在的位置: 首页 > 综合 > 正文

python调用 C/C++ 代码示例

2013年12月15日 ⁄ 综合 ⁄ 共 1488字 ⁄ 字号 评论关闭

Python开发效率高,运行效率低。而c/c++恰恰相反。因此在python脚本中调用c/c++的库,对python进行扩展,是很有必要的。使用python api,http://www.python.org/doc/,需要安装python-dev。
test.cpp文件如下

[cpp]
  1. #include <usr/include/python2.7/Python.h> //包含python的头文件  
  2. // 1 c/cpp中的函数  
  3. int my_c_function(const char *arg) {  
  4.   int n = system(arg);  
  5.   return n;  
  6. }  
  7. // 2 python 包装  
  8. static PyObject * wrap_my_c_fun(PyObject *self, PyObject *args) {  
  9.   const char * command;  
  10.   int n;  
  11.   if (!PyArg_ParseTuple(args, "s", &command))//这句是把python的变量args转换成c的变量command  
  12.     return NULL;  
  13.   n = my_c_function(command);//调用c的函数  
  14.   return Py_BuildValue("i", n);//把c的返回值n转换成python的对象  
  15. }  
  16. // 3 方法列表  
  17. static PyMethodDef MyCppMethods[] = {  
  18.     //MyCppFun1是python中注册的函数名,wrap_my_c_fun是函数指针  
  19.     { "MyCppFun1", wrap_my_c_fun, METH_VARARGS, "Execute a shell command." },  
  20.     { NULL, NULL, 0, NULL }  
  21. };  
  22. // 4 模块初始化方法  
  23. PyMODINIT_FUNC initMyCppModule(void) {  
  24.   //初始模块,把MyCppMethods初始到MyCppModule中  
  25.   PyObject *m = Py_InitModule("MyCppModule", MyCppMethods);  
  26.   if (m == NULL)  
  27.     return;  
  28. }  

 

make:

g++ -shared -fpic test.cpp -o MyCppModule.so

编译完毕后,目录下会有一个MyCppModule.so文件

 

test.py文件如下

[python]
  1. # -*- coding: utf-8 -*-  
  2. import MyCppModule  
  3. #导入python的模块(也就是c的模块,注意so文件名是MyCppModule    
  4. r = MyCppModule.MyCppFun1("ls -l")  
  5. print r   
  6. print "OK"    

 

执行

lhb@localhost:~/maplib/clib/pyc/invokec$ python test.py
总计 20
-rwxr-xr-x 1 lhb lhb   45 2010-08-11 17:45 make
-rwxr-xr-x 1 lhb lhb 7361 2010-08-12 10:14 MyCppModule.so
-rw-r--r-- 1 lhb lhb  979 2010-08-11 17:45 test.cpp
-rw-r--r-- 1 lhb lhb  181 2010-08-11 17:45 test.py
0
OK

【上篇】
【下篇】

抱歉!评论已关闭.