Python调用C/C++的方法解析


Posted in Python onAugust 05, 2020

Python是解释性语言, 底层就是用c实现的, 所以用python调用C是很容易的, 下面就总结一下各种调用的方法, 给出例子, 所有例子都在ubuntu9.10, python2.6下试过.

1. Python 调用 C (base)

想在python中调用c函数, 如这儿的fact

#include <Python.h>

int fact(int n)
{
 if (n <= 1)
 return 1;
 else
 return n * fact(n - 1);
}

PyObject* wrap_fact(PyObject* self, PyObject* args)
{
 int n, result;

 if (! PyArg_ParseTuple(args, "i:fact", &n))
 return NULL;
 result = fact(n);
 return Py_BuildValue("i", result);
}

static PyMethodDef exampleMethods[] =
{
 {"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
 {NULL, NULL}
};

void initexample()
{
 PyObject* m;
 m = Py_InitModule("example", exampleMethods);
}

把这段代码存为wrapper.c, 编成so库,

gcc -fPIC wrapper.c -o example.so -shared  -I/usr/include/python2.6 -I/usr/lib/python2.6/config

 然后在有此so库的目录, 进入python, 可以如下使用

import example

example.fact(4)

2. Python 调用 C++ (base)

在python中调用C++类成员函数, 如下调用TestFact类中的fact函数,

#include <Python.h>

class TestFact{
 public:
 TestFact(){};
 ~TestFact(){};
 int fact(int n);
};

int TestFact::fact(int n)
{
 if (n <= 1)
 return 1;
 else
 return n * (n - 1);
}

int fact(int n)
{
 TestFact t;
 return t.fact(n);
}

PyObject* wrap_fact(PyObject* self, PyObject* args)
{
 int n, result;

 if (! PyArg_ParseTuple(args, "i:fact", &n))
 return NULL;
 result = fact(n);
 return Py_BuildValue("i", result);
}

static PyMethodDef exampleMethods[] =
{
 {"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
 {NULL, NULL}
};

extern "C"    //不加会导致找不到initexample
void initexample()
{
 PyObject* m;
 m = Py_InitModule("example", exampleMethods);
}

 把这段代码存为wrapper.cpp, 编成so库,

g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config

 然后在有此so库的目录, 进入python, 可以如下使用

import example

example.fact(4)

 3. Python 调用 C++ (Boost.Python)

Boost库是非常强大的库, 其中的python库可以用来封装c++被python调用, 功能比较强大, 不但可以封装函数还能封装类, 类成员.

http://dev.gameres.com/Program/Abstract/Building%20Hybrid%20Systems%20with%20Boost_Python.CHN.by.JERRY.htm

首先在ubuntu下安装boost.python, apt-get install libboost-python-dev

#include <boost/python.hpp>
char const* greet()
{
 return "hello, world";
}

BOOST_PYTHON_MODULE(hello)
{
 using namespace boost::python;
 def("greet", greet);
}

把代码存为hello.cpp, 编译成so库

g++ hello.cpp -o hello.so -shared -I/usr/include/python2.5 -I/usr/lib/python2.5/config -lboost_python-gcc42-mt-1_34_1

 此处python路径设为你的python路径, 并且必须加-lboost_python-gcc42-mt-1_34_1, 这个库名不一定是这个, 去/user/lib查

 然后在有此so库的目录, 进入python, 可以如下使用

>>> import hello
>>> hello.greet()
'hello, world'

 4. python 调用 c++ (ctypes)

ctypes is an advanced ffi (Foreign Function Interface) packagefor Python 2.3 and higher. In Python 2.5 it is alreadyincluded.

ctypes allows to call functions in dlls/shared libraries and hasextensive facilities to create, access and manipulate simple andcomplicated C data types in Python - in other words: wraplibraries in pure Python. It is even possible to implement Ccallback functions in pure Python.

http://python.net/crew/theller/ctypes/

 
#include <Python.h>

class TestFact{
 public:
 TestFact(){};
 ~TestFact(){};
 int fact(int n);
};

int TestFact::fact(int n)
{
 if (n <= 1)
 return 1;
 else
 return n * (n - 1);
}

extern "C"
int fact(int n)
{
 TestFact t;
 return t.fact(n);
}

将代码存为wrapper.cpp不用写python接口封装, 直接编译成so库,

g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config

 进入python, 可以如下使用

>>> import ctypes
>>> pdll = ctypes.CDLL('/home/ubuntu/tmp/example.so')
>>> pdll.fact(4)
12

到此这篇关于Python调用C/C++的方法解析的文章就介绍到这了,更多相关Python调用C/C++的方法内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python中用于返回绝对值的abs()方法
May 14 Python
CentOS中升级Python版本的方法详解
Jul 10 Python
python 通过字符串调用对象属性或方法的实例讲解
Apr 21 Python
Django实现支付宝付款和微信支付的示例代码
Jul 25 Python
浅述python中深浅拷贝原理
Sep 18 Python
通过shell+python实现企业微信预警
Mar 07 Python
Python3.5装饰器原理及应用实例详解
Apr 30 Python
淘宝秒杀python脚本 扫码登录版
Sep 19 Python
python使用python-pptx删除ppt某页实例
Feb 14 Python
使用tensorflow根据输入更改tensor shape
Jun 23 Python
Python ellipsis 的用法详解
Nov 20 Python
python超详细实现完整学生成绩管理系统
Mar 17 Python
浅谈Python3中print函数的换行
Aug 05 #Python
基于Python编写一个计算器程序,实现简单的加减乘除和取余二元运算
Aug 05 #Python
python中逻辑与或(and、or)和按位与或异或(&amp;、|、^)区别
Aug 05 #Python
Node.js 和 Python之间该选择哪个?
Aug 05 #Python
基于python图书馆管理系统设计实例详解
Aug 05 #Python
基于Python的一个自动录入表格的小程序
Aug 05 #Python
Python中logging日志记录到文件及自动分割的操作代码
Aug 05 #Python
You might like
PHP实现微信发红包程序
2015/08/24 PHP
php自动提交表单的方法(基于fsockopen与curl)
2016/05/09 PHP
分享几种好用的PHP自定义加密函数(可逆/不可逆)
2020/09/15 PHP
下载网站打开页面后间隔多少时间才显示下载链接地址的代码
2010/04/25 Javascript
用JS判别浏览器种类以及IE版本的几种方法小结
2011/08/02 Javascript
自己动手制作jquery插件之自动添加删除行的实现
2011/10/13 Javascript
等待指定时间后自动跳转或关闭当前页面的js代码
2013/07/09 Javascript
js中如何把字符串转化为对象、数组示例代码
2013/07/17 Javascript
JS获取农历日期具体实例
2013/11/14 Javascript
Jquery在指定DIV加载HTML示例代码
2014/02/17 Javascript
javascript汉字拼音互转的简单实例
2016/10/09 Javascript
基于jQuery和CSS3实现APPLE TV海报视差效果
2017/06/16 jQuery
最通俗易懂的javascript变量提升详解
2017/08/05 Javascript
编写React组件项目实践分析
2018/03/04 Javascript
Javascript 实现 Excel 导入生成图表功能
2018/10/22 Javascript
layui禁用侧边导航栏点击事件的解决方法
2019/09/25 Javascript
Vue.js中的高级面试题及答案
2020/01/13 Javascript
京东优选小程序的实现代码示例
2020/02/25 Javascript
ESLint 是如何检查 .vue 文件的
2020/11/30 Vue.js
js实现碰撞检测
2021/01/29 Javascript
[01:18:31]DOTA2-DPC中国联赛定级赛 LBZS vs Magma BO3第一场 1月10日
2021/03/11 DOTA
Python基于pygame实现图片代替鼠标移动效果
2015/11/11 Python
Python中的列表生成式与生成器学习教程
2016/03/13 Python
Python入门之三角函数全解【收藏】
2017/11/08 Python
将python运行结果保存至本地文件中的示例讲解
2019/07/11 Python
python numpy矩阵信息说明,shape,size,dtype
2020/05/22 Python
使用CSS3的font-face字体嵌入样式的方法讲解
2016/05/13 HTML / CSS
HTML5制作3D爱心动画教程 献给女友浪漫的礼物
2014/11/05 HTML / CSS
美国家具网站:Cymax
2016/09/17 全球购物
美国在线自行车商店:Jenson USA
2018/05/22 全球购物
德国运动营养和健身网上商店:Myprotein.de
2018/07/18 全球购物
工地安全质量标语
2014/06/07 职场文书
爬山的活动方案
2014/08/16 职场文书
2015年七一建党节活动总结
2015/03/20 职场文书
2015年世界急救日宣传活动方案
2015/05/06 职场文书
教师师德工作总结2015
2015/07/22 职场文书