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使用rsa加密算法模块模拟新浪微博登录
Jan 22 Python
Fabric 应用案例
Aug 28 Python
python 编写简单网页服务器的实例
Jun 01 Python
详解利用django中间件django.middleware.csrf.CsrfViewMiddleware防止csrf攻击
Oct 09 Python
Python比较配置文件的方法实例详解
Jun 06 Python
Python 根据日志级别打印不同颜色的日志的方法示例
Aug 08 Python
django drf框架中的user验证以及JWT拓展的介绍
Aug 12 Python
python tkinter组件使用详解
Sep 16 Python
Python实现点云投影到平面显示
Jan 18 Python
在ipython notebook中使用argparse方式
Apr 20 Python
AI:如何训练机器学习的模型
Apr 16 Python
python+opencv实现视频抽帧示例代码
Jun 11 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
关于更改Zend Studio/Eclipse代码风格主题的介绍
2013/06/23 PHP
ThinkPHP2.0读取MSSQL提示Incorrect syntax near the keyword 'AS'的解决方法
2014/06/25 PHP
修改ThinkPHP缓存为Memcache的方法
2014/06/25 PHP
PHP与Ajax相结合实现登录验证小Demo
2016/03/16 PHP
Smarty分页实现方法完整实例
2016/05/11 PHP
XHProf报告字段含义的解析
2016/05/17 PHP
laravel 框架实现无限级分类的方法示例
2019/10/31 PHP
许愿墙中用到的函数
2006/10/07 Javascript
禁止刷新,回退的JS
2006/11/25 Javascript
JS实现的最简Table选项卡效果
2015/10/14 Javascript
基于JavaScript实现鼠标向下滑动加载div的代码
2016/08/31 Javascript
jquery.validate表单验证插件使用详解
2017/06/21 jQuery
基于javascript 显式转换与隐式转换(详解)
2017/12/15 Javascript
详解vue2.0+vue-video-player实现hls播放全过程
2018/03/02 Javascript
AngularJS 多指令Scope问题的解决
2018/10/25 Javascript
jquery无缝图片轮播组件封装
2020/11/25 jQuery
基于JavaScript获取url参数2种方法
2020/04/17 Javascript
vue 组件简介
2020/07/31 Javascript
[01:06]欢迎来到上海,TI9
2018/08/26 DOTA
使用PDB模式调试Python程序介绍
2015/04/05 Python
python基于Tkinter库实现简单文本编辑器实例
2015/05/05 Python
Python操作SQLite数据库的方法详解
2017/06/16 Python
django 2.0更新的10条注意事项总结
2018/01/05 Python
python 字典的打印实现
2019/09/26 Python
python matplotlib折线图样式实现过程
2019/11/04 Python
Python读写锁实现实现代码解析
2020/11/28 Python
收集的7个CSS3代码生成工具
2010/04/17 HTML / CSS
html5的画布canvas——画出弧线、旋转的图形实例代码+效果图
2013/06/09 HTML / CSS
《她是我的朋友》教学反思
2014/04/26 职场文书
公司总经理任命书
2014/06/05 职场文书
关键在于落实心得体会
2014/09/03 职场文书
2014年自愿离婚协议书范本
2014/09/25 职场文书
房屋财产继承协议书范本
2014/11/03 职场文书
2015年妇委会工作总结
2015/05/22 职场文书
个人借条范本
2015/05/25 职场文书
手把手教你实现PyTorch的MNIST数据集
2021/06/28 Python