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 相关文章推荐
linux环境下安装pyramid和新建项目的步骤
Nov 27 Python
pymssql数据库操作MSSQL2005实例分析
May 25 Python
python DataFrame获取行数、列数、索引及第几行第几列的值方法
Apr 08 Python
Python引用计数操作示例
Aug 23 Python
python通过tcp发送xml报文的方法
Dec 28 Python
python里 super类的工作原理详解
Jun 19 Python
pytorch实现特殊的Module--Sqeuential三种写法
Jan 15 Python
Python安装tar.gz格式文件方法详解
Jan 19 Python
关于PyCharm安装后修改路径名称使其可重新打开的问题
Oct 20 Python
Python和Bash结合在一起的方法
Nov 13 Python
python爬取豆瓣电影TOP250数据
May 23 Python
Python实现生成bmp图像的方法
Jun 13 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 遍历文件实现代码
2011/05/04 PHP
php之CodeIgniter学习笔记
2013/06/17 PHP
dedecms函数分享之获取某一栏目所有子栏目
2014/05/19 PHP
yii中widget的用法
2014/12/03 PHP
Jquery 最近浏览过的商品的功能实现代码
2010/05/14 Javascript
JavaScript高级程序设计 读书笔记之十一 内置对象Global
2012/03/07 Javascript
在浏览器窗口上添加遮罩层的方法
2012/11/12 Javascript
JS localStorage实现本地缓存的方法
2013/06/22 Javascript
使用GruntJS构建Web程序之Tasks(任务)篇
2014/06/06 Javascript
js 获取站点应用名的简单实例
2016/08/18 Javascript
jQuery validate插件功能与用法详解
2016/12/15 Javascript
使用vue-route 的 beforeEach 实现导航守卫(路由跳转前验证登录)功能
2018/03/22 Javascript
如何使用CSS3和JQuery easing 插件制作绚丽菜单
2019/06/18 jQuery
JQuery 实现文件下载的常用方法分析
2019/10/29 jQuery
Python中Random和Math模块学习笔记
2015/05/18 Python
python opencv设置摄像头分辨率以及各个参数的方法
2018/04/02 Python
详解python之协程gevent模块
2018/06/14 Python
在macOS上搭建python环境的实现方法
2019/08/13 Python
如何为Python终端提供持久性历史记录
2019/09/03 Python
解决python web项目意外关闭,但占用端口的问题
2019/12/17 Python
python str字符串转uuid实例
2020/03/03 Python
Win10用vscode打开anaconda环境中的python出错问题的解决
2020/05/25 Python
python中if及if-else如何使用
2020/06/02 Python
Python爬虫实现HTTP网络请求多种实现方式
2020/06/19 Python
解决Django响应JsonResponse返回json格式数据报错问题
2020/08/09 Python
Pytho爬虫中Requests设置请求头Headers的方法
2020/09/22 Python
python日志通过不同的等级打印不同的颜色(示例代码)
2021/01/13 Python
澳大利亚礼品卡商店:Gift Card Store
2019/06/24 全球购物
高中同学聚会邀请函
2014/01/11 职场文书
卫校中专生的自我评价
2014/01/15 职场文书
致100米运动员广播稿
2014/02/14 职场文书
班主任工作经验交流材料
2014/05/13 职场文书
2014企业年终工作总结
2014/12/23 职场文书
开票证明
2015/06/23 职场文书
MySQL索引失效的典型案例
2021/06/05 MySQL
gojs实现蚂蚁线动画效果
2022/02/18 Javascript