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

时间: 2024-07-30 10:15:31

Python调用C/C++的种种方法的相关文章

Python调用系统命令的6种方法

Python调用系统命令的6种方法在Python中调用系统命令一般使用os或者subprocess模块,下面介绍Python中最常用的6种调用系统命令的方法.1.os.system()该函数返回命令执行结果的返回值,system()函数在执行过程中进行了以下三步操作:1.fork一个子进程:2.在子进程中调用exec函数去执行命令:3.在父进程中调用wait(阻塞)去等待子进程结束.返回0表示命令执行成功,其他表示失败.用法:os.system("command")2.os.popen

测试:python调用cmd命令三种方法

目前我使用到的python中执行cmd的方式有三种 使用os.system("cmd") 该方法在调用完shell脚本后,返回一个16位的二进制数,低位为杀死所调用脚本的信号号码,高位为脚本的退出状态码,即脚本中"exit 1"的代码执行后,os.system函数返回值的高位数则是1,如果低位数是0的情况下,则函数的返回值是0×100,换算为10进制得到256. 如果我们需要获得os.system的正确返回值,那使用位移运算可以还原返回值: >>>

Python调用C/C++动态链接库的方法

本文以实例讲解了Python调用C/C++ DLL动态链接库的方法,具体示例如下: 示例一: 首先,在创建一个DLL工程(本例创建环境为VS 2005),头文件: //hello.h #ifdef EXPORT_HELLO_DLL #define HELLO_API __declspec(dllexport) #else #define HELLO_API __declspec(dllimport) #endif extern "C" { HELLO_API int IntAdd(in

python 调用shell命令三种方法

#!/usr/bin/python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器: #!/usr/bin/env python这种用法是为了防止操作系统用户没有将python装在默认的/usr/bin路径里. python调用shell命令的方法有许多 1.1   os.system(command) 在一个子shell中运行command命令,并返回command命令执行完毕后的退出状态.这实际上是使用C标准库函数system()实现的.这个函数在执行comman

python调用shell命令之三大方法

preface: 忙于最近的任务,需要用到libsvm的一些命令,如在终端运行java svm_train train_file model_file. pythonsubset.py file train_num train_file test_file等命令,但file的准备又是通过python写好的,file需要是libsvm能够接受的格式,故用python写好特征,转为libsvm能够接受的格式,生成file,然后在终端调用训练.故想着直接在python代码里面直接运行终端的命令.博友博

Python调用系统命令的四种方法

一.os.system(commandString) import os statusCode=os.system("powershell sleep 3 ;echo 天下大势为我所控") print("over",statusCode) 这里使用了powershell来执行sleep命令,在cmd里面是没有sleep命令的. 会发现os.system(commandString)是阻塞的. 这个函数类似C语言里面的stdlib.h中的system命令 这种方法只负

编写python调用dubbo接口hessian协议的例子

引子 今天有小伙伴问到了怎么用python调用dubbo的接口的方法,就随便写了这么一篇文章.其实dubbo接口可以使用loadrunner.jmeter等完成,最好是熟悉java语言的,那么编写起来就丝滑了很多哦 那么用python来调用其实也是很简单的,并不像大家想的那么复杂,基本3.4步就可以搞定,不要急,来看如何实现 接口说明 既然做接口测试,那接口的说明是必须的,问开发GG要,不要问从哪里来....大致包括如下内容: 接口地址 http://192.168.133.129:20880/

python调用父类方法

本文和大家分享的主要是python开发中,调用父类的两种方法异同点,希望对大家学习和使用python语言有所帮助. python中有两种方法可以调用父类的方法: super(Child, self).method(args) 和Parent.method(self, args) .我用其中的一种报了如下错误: 找不到 classobj .当我把调用改为 super(B, self).f(name) 就能正确运行,且结果正确. 分析错误 因为基类没有继承 object , 在python中,一个可

python 调用shell命令的方法

在python程序中调用shell命令,是件很酷且常用的事情…… 1. os.system(command) 此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出状态,如果command有执行内容,会在标准输出显示.这实际上是使用C标准库函数system()实现的. 缺点:这个函数在执行command命令时需要重新打开一个终端,并且无法保存command命令的执行结果. 实例:os.system('ls -l *') 2. os.popen(command,