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. Java多线程相关知识

    1)wait()  notify()  sleep() sleep是Thread类的函数,wait和notify是Object的函数. sleep的时候keep对象锁,wait的时候release 对 ...

  2. ZOJ 3261 - Connections in Galaxy War ,并查集删边

    In order to strengthen the defense ability, many stars in galaxy allied together and built many bidi ...

  3. Inno Setup教程

    一.简介 Inno Setup是一款免费的安装制作软件,小巧.简便.精美是其最大特点,支持pascal脚本,能快速制作出标准Windows2000风格的安装界面,足以完成一般安装任务.该软件用Delp ...

  4. [置顶] 学习鸟哥的Linux私房菜笔记(6)——过滤器、输入输出及管道

    一.过滤器 Linux中的应用工具分为三种: 交互工具 过滤器 编辑器 能够接受数据,过滤再输出的工具,称之为过滤器 对过滤器和进程,存在着输入源与输出对象 二.输入.输出.重定向 输入:过滤器的数据 ...

  5. python 自定义信号处理器

    说明: 这里所说的信号与kill 命令中的信号指的是同一个. #!/usr/bin/python #!coding:utf-8 import sys,time,signal def now(): re ...

  6. 【PAT】1012. The Best Rank (25)

    题目链接: http://pat.zju.edu.cn/contests/pat-a-practise/1012 题目描述: To evaluate the performance of our fi ...

  7. sql server操作2:查询数据库语句大全【转】

    注:以下操作均建立在上篇文章sql Server操作1的数据基础之上 一.实验目的 熟悉SQL语句的基本使用方法,学习如何编写SQL语句来实现查询 二.实验内容和要求 使用SQL查询分析器查询数据,练 ...

  8. _00023 Kafka 奇怪的操作_001它们的定义Encoder达到Class数据传输水平和决心

    博文作者:妳那伊抹微笑 博客地址:http://blog.csdn.net/u012185296 博文标题:_00023 Kafka 诡异操作_001自己定义Encoder实现Class级别的数据传送 ...

  9. 警告框和操作表(IOS开发)

    警告框(AlertView)时模态的,不关闭它就不能做其它事情,所以不是下面几种情况不应该随便使用. 1.应用不能继续执行. 如内存不足,没有网络.一般仅仅须要一个button. 2.询问还有一个解决 ...

  10. javascript高级知识点——函数的长度

    代码信息来自于http://ejohn.org/apps/learn/. 函数的长度属性如何工作? function makeNinja(name){} function makeSamurai(na ...