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二分法搜索算法实例分析
May 11 Python
Python字符串特性及常用字符串方法的简单笔记
Jan 04 Python
Python循环语句中else的用法总结
Sep 11 Python
python监控linux内存并写入mongodb(推荐)
Sep 11 Python
Python实现字符串匹配算法代码示例
Dec 05 Python
Win7 64位下python3.6.5安装配置图文教程
Oct 27 Python
Python结合ImageMagick实现多张图片合并为一个pdf文件的方法
Apr 24 Python
PySide和PyQt加载ui文件的两种方法
Feb 27 Python
python3.x+pyqt5实现主窗口状态栏里(嵌入)显示进度条功能
Jul 04 Python
基于keras中的回调函数用法说明
Jun 17 Python
python Pexpect模块的使用
Dec 25 Python
Python基础之pandas数据合并
Apr 27 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
thinkphp中连接oracle时封装方法无法用的解决办法
2013/06/17 PHP
浅析php插件 Simple HTML DOM 用DOM方式处理HTML
2013/07/01 PHP
md5 16位二进制与32位字符串相互转换示例
2013/12/30 PHP
探寻PHP脚本不报错的原因
2014/06/12 PHP
PHP实现Unicode编码相互转换的方法示例
2020/11/17 PHP
js实现图片在未加载完成前显示加载中字样
2014/09/03 Javascript
JavaScript中exec函数用法实例分析
2015/06/08 Javascript
JavaScript实战之菜单特效
2016/08/16 Javascript
vuejs手把手教你写一个完整的购物车实例代码
2017/07/06 Javascript
Vuejs在v-for中,利用index来对第一项添加class的方法
2018/03/03 Javascript
vue的diff算法知识点总结
2018/03/29 Javascript
微信小程序实现美团菜单
2018/06/06 Javascript
微信小程序实现单选功能
2018/10/30 Javascript
详解微信小程序支付流程与梳理
2019/07/16 Javascript
vue-froala-wysiwyg 富文本编辑器功能
2019/09/19 Javascript
在vue中使用Echarts利用watch做动态数据渲染操作
2020/07/20 Javascript
[51:20]完美世界DOTA2联赛PWL S2 Magma vs PXG 第一场 11.28
2020/12/01 DOTA
[01:23:45]DOTA2-DPC中国联赛 正赛 CDEC vs Dragon BO3 第一场 1月22日
2021/03/11 DOTA
Python contextlib模块使用示例
2015/02/18 Python
简单介绍Python中的RSS处理
2015/04/13 Python
python类继承用法实例分析
2015/05/27 Python
Python实现的RSS阅读器实例
2015/07/25 Python
深入理解Python中命名空间的查找规则LEGB
2015/08/06 Python
使用Python读取大文件的方法
2018/02/11 Python
python语言中with as的用法使用详解
2018/02/23 Python
Python3.遍历某文件夹提取特定文件名的实例
2018/04/26 Python
Python利用多线程同步锁实现多窗口订票系统(推荐)
2019/12/22 Python
Python生成并下载文件后端代码实例
2020/08/31 Python
Nobody Denim官网:购买高级女士牛仔裤
2021/03/15 全球购物
村委会贫困证明范本
2014/09/17 职场文书
学生上课看漫画的检讨书
2014/09/26 职场文书
2015届大学生就业推荐表自我评价
2014/09/27 职场文书
安全生产标语大全
2014/10/06 职场文书
旷课检讨书500字
2014/10/14 职场文书
团组织关系介绍信
2019/06/24 职场文书
详解Html5项目适配系统深色模式方案总结
2021/04/14 HTML / CSS