Python中调用C++函数

本文介绍如何通过Python API在Python脚本中调用C/C++库,提高Python的运行效率。具体步骤包括:编写C/C++源代码、定义Python可调用的包装函数、创建方法列表并初始化模块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.youkuaiyun.com/marising/article/details/2845339

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值