Python调用C/C++的种种方法

2010-12-07 09:59 28433人阅读 评论(1) 收藏

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) package for Python 2.3 and higher. In Python 2.5 it is already included.

ctypes allows to call functions in dlls/shared libraries and has extensive facilities to create, access and manipulate simple and complicated C data types in Python - in other words: wrap libraries in pure Python. It is even possible to implement C callback 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++的种种方法的更多相关文章

  1. Python调用C/C++动态链接库的方法详解

    Python调用C/C++动态链接库的方法详解 投稿:shichen2014 这篇文章主要介绍了Python调用C/C++动态链接库的方法,需要的朋友可以参考下 本文以实例讲解了Python调用C/C ...

  2. python 调用shell命令三种方法

    #!/usr/bin/python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器: #!/usr/bin/env python这种用法是为了防止操作系统用户没有将pyth ...

  3. python调用html内的js方法

    这方面资料不多,不懂html,不懂js,略懂python的我,稍微看了点html和js,好几天的摸索,终于测试成功了. PYQT+HTML利用PYQT的webview调用JS内方法 1.python调 ...

  4. python调用其他程序或脚本方法(转)

    python运行(调用)其他程序或脚本 在Python中可以方便地使用os模块运行其他的脚本或者程序,这样就可以在脚本中直接使用其他脚本,或者程序提供的功能,而不必再次编写实现该功能的代码.为了更好地 ...

  5. Python调用jar包中的方法

    [本文出自天外归云的博客园] 需求 最近在后台项目代码中一段自定义的AES加解密的程序在平时的测试工作中应用频繁.因为写脚本经常会需要使用,而经过各种尝试,比如jpype等,都不尽如人意.最后转换思路 ...

  6. python 调用内部类的两种方法

    class Car:#外部类 class Door:#内部类 def open(self): print('open door') class Wheel: def run(self): print( ...

  7. python 调用 C++ code

    本文以实例code讲解python 调用 C++的方法. 1. 如果没有参数传递从python传递至C++,python调用C++的最简单方法是将函数声明为C可用函数,然后作为C code被pytho ...

  8. python调用.so

    python调用动态链接库的基本过程 动态链接库在Windows中为.dll文件,在linux中为.so文件.以linux平台为例说明python调用.so文件的使用方法. 本例中默认读者已经掌握动态 ...

  9. 【转】Python调用C语言动态链接库

    转自:https://www.cnblogs.com/fariver/p/6573112.html 动态链接库在Windows中为.dll文件,在linux中为.so文件.以linux平台为例说明py ...

随机推荐

  1. Marshal 类的内存操作的一般功能

    Marshal类 提供了一个方法集,这些方法用于分配非托管内存.复制非托管内存块.将托管类型转换为非托管类型,此外还提供了在与非托管代码交互时使用的其他杂项方法. 命名空间:System.Runtim ...

  2. 一个可以拓展的垂直多级导航栏 Demo

    大四党忙忙碌碌找工作,博客荒废久矣,可谓:终日昏昏醉梦间,忽闻春尽强登山.因过竹院逢僧话,偷得浮生半日闲. 这是个垂直的导航栏,可以有无限多层的子级菜单,看代码注释就够了: <!DOCTYPE ...

  3. mysql校对规则引起的不区分大小写

    CREATE TABLE `staticcatalogue` ( `Source` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL ...

  4. Android显示YUV图像

    需要流畅显示YUV图像需要使用Opengl库调用GPU资源,网上在这部分的资料很少.实际上Android已经为我们提供了相关的Opengl方法 主体过程如下: 1.建立GLSurfaceView 2. ...

  5. jQuery 中使用 JSON

    转载:http://www.cnblogs.com/haogj/archive/2011/12/01/2271098.html JSON 格式 json 是 Ajax 中使用频率最高的数据格式,在浏览 ...

  6. 【自学php】第二天 - php快速入门

    打算看<php和mysql web开发>来学习php,所以也算是这本书的学习笔记吧,也按照书里的例子来练习,但是也有些取舍.第一章是一个订单表单的例子,php用于处理提交的表单. 1.先创 ...

  7. java代码收藏:获取HttpServletRequest中某一前缀的参数

    public static Map getParametersStartingWith(ServletRequest request, String prefix) { Enumeration par ...

  8. DIV+CSS规范命名

    一.命名规则说明: 1).所有的命名最好都小写2).属性的值一定要用双引号("")括起来,且一定要有值如class="divcss5",id="div ...

  9. 在Oracle中使用sql获取数据库名称

    在Oracle中使用sql获取当前数据库名称 select name from v$database;

  10. [置顶] Mysql存储过程入门知识

    Mysql存储过程入门知识 #1,查看数据库所有的存储过程名 #--这个语句被用来移除一个存储程序.不能在一个存储过程中删除另一个存储过程,只能调用另一个存储过程 #SELECT NAME FROM ...