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的@property装饰器的用法
Apr 28 Python
Python使用defaultdict读取文件各列的方法
May 11 Python
Python实现列表删除重复元素的三种常用方法分析
Nov 24 Python
使用C++扩展Python的功能详解
Jan 12 Python
pandas将numpy数组写入到csv的实例
Jul 04 Python
Python分割指定页数的pdf文件方法
Oct 26 Python
python实现文件的分割与合并
Aug 29 Python
使用Rasterio读取栅格数据的实例讲解
Nov 26 Python
Python数据结构dict常用操作代码实例
Mar 12 Python
keras输出预测值和真实值方式
Jun 27 Python
基于opencv的selenium滑动验证码的实现
Jul 24 Python
python产生模拟数据faker库的使用详解
Nov 04 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
英雄试炼之肉山谷—引领RPG新潮流
2020/04/20 DOTA
PHP下通过系统信号量加锁方式获取递增序列ID
2009/09/25 PHP
php使用pack处理二进制文件的方法
2014/07/03 PHP
php获取远程文件内容的函数
2015/11/02 PHP
详谈symfony window下的安装 安装时候出现的问题以及解决方法
2017/09/28 PHP
PHP实现统计所有字符在字符串中出现次数的方法
2017/10/17 PHP
yii2.0框架数据库操作简单示例【添加,修改,删除,查询,打印等】
2020/04/13 PHP
编写自己的jQuery插件简单实现代码
2011/04/19 Javascript
javascript当中的代码嗅探扩展原生对象和原型(prototype)
2013/01/11 Javascript
基于jQuery实现仿QQ空间送礼物功能代码
2016/05/24 Javascript
创建一般js对象的几种方式
2017/01/19 Javascript
JavaScript数组push方法使用注意事项
2017/10/30 Javascript
swiper自定义分页器使用方法详解
2020/09/14 Javascript
微信小程序修改checkbox的样式代码实例
2020/01/21 Javascript
详解React的回调渲染模式
2020/09/10 Javascript
angular *Ngif else用法详解
2020/12/15 Javascript
JavaScript 中的执行上下文和执行栈实例讲解
2021/02/25 Javascript
[00:52]玛尔斯技能全介绍
2019/03/06 DOTA
[47:03]完美世界DOTA2联赛PWL S3 access vs LBZS 第一场 12.20
2020/12/23 DOTA
Python入门篇之面向对象
2014/10/20 Python
Python下Fabric的简单部署方法
2015/07/14 Python
Python中动态创建类实例的方法
2017/03/24 Python
[原创]教女朋友学Python(一)运行环境搭建
2017/11/29 Python
Python中生成一个指定长度的随机字符串实现示例
2019/11/06 Python
pytorch SENet实现案例
2020/06/24 Python
九州传奇上机题
2014/07/10 面试题
财务管理个人自荐书范文
2013/11/24 职场文书
中文专业毕业生自荐书范文
2014/01/04 职场文书
小溪流的歌教学反思
2014/02/13 职场文书
行政主管职责范本
2014/03/07 职场文书
个人委托书范文
2015/01/28 职场文书
民事上诉状范文
2015/05/22 职场文书
迎新年主持词
2015/07/06 职场文书
2015年文秘个人工作总结
2015/10/14 职场文书
Requests什么的通通爬不了的Python超强反爬虫方案!
2021/05/20 Python
实现AJAX异步调用和局部刷新的基本步骤
2022/03/17 Javascript