Python中調用C++函數

Python開發效率高,運行效率低。而c/c++恰恰相反。因此在python腳本中調用c/c++的庫,對python進行擴展,是很有必要的。使用python api,http://www.python.org/doc/ ,需要安裝python-dev。
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


http://blog.csdn.net/marising/article/details/2845339

http://www.th7.cn/Program/Python/2011-07-07/29384.shtml

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章