使用C++来写Python扩展模块
2011-11-03 21:19
906 查看
1.起因
众所周知,python在处理一些计算量大的任务时效率很低,不仅仅是执行速率,还有内存占用上,比如下面一段代码就可以让你的电脑卡得不行:
alist = [i for i in xrange(1024*1024*1024)]
所以有的时候还是得借助C/C++来增强Python的效率。
2.方法
我所知道的大概有三种常用方法:
1>使用ctypes模块来调用C写的共享库,比如:
#测试ctypes调用linux动态库的能力
from ctypes import *
lib = CDLL("libc.so.6")
printf = lib.printf
printf("Hello World\n")
#查找动态库
from ctypes.util import find_library
print find_library('c')
output = CDLL(find_library("c")).printf
output("测试成功!\n")
但是用它来调用C++写的so就不太合适,因为编译时c++函数名修饰会给你的函数取一个特殊的字符串,你不能在你的python代码里直接使用此函数名,除非你使用的是修饰后的函数名。(在linux下你可以用nm来查看so中的函数名)
2>用C来写python的扩展模块,这个没怎么用过,以后使用时再记录在此。
3>用C++来写python扩展模块:
我是使用Boost.Python来写扩展的,先上工作中的代码片段:
#include <boost/python.hpp> //包含boost.python头文件
#include <cstdio>
#include <string>
using namespace boost::python;//引入命令空间
class lshw //定义一个类
{
public:
lshw();
virtual ~lshw();
void scan_device();
string get_xml();
private:
hwNode *computer;
};
lshw::lshw()
{
computer = new hwNode("computer", hw::system);
}
lshw::~lshw()
{
if (computer)
delete computer;
}
void lshw::scan_device()
{
enable("output:numeric");
disable("output:sanitize");
scan_system(*computer);
}
string lshw::get_xml()
{
return computer->asXML();
}
void hello()
{
std::cout << "Hello World!" <<std::endl;
}
BOOST_PYTHON_MODULE(lshw)
{
class_<lshw, boost::noncopyable > ("lshw", "This is a lshw project python extend", init<>())//导出类中的方法
.def("scan_device", &lshw::scan_device)
.def("get_xml", &lshw::get_xml)
;
def("hello",&hello);//导出方法
}
使用boost.python其实结构很简单,你只要写很少的boost.python的代码,你可以把大部分的精力放在C++功能代码上,花很少的精力就可以把它扩展成python的模块。下面是我在Ubuntu11.10上的编译过程:
首先安装boost.python:
sudo apt-get install libboost-python1.46.1
再来编译生成so共享库文件:
g++ -shared -fPIC lshw.cc -o lshw.so -lboost_python
使用:
import lshw
hw = lshw.lshw()
lshw.hello()
hw.scan_device()
xml = self.hw.get_xml()
当然,lshw.so和你的py文件要让在同一目录下,或者你可以把它放在/usr/lib/python2.7/dist-packages/目录下,你就可以在系统的任何地方加载它了。这段代码仅仅是展示一下boost.python的使用方法,并没有实际的意义,也无法编译通过,只是一个简单的模型。
1.总结
Boost.Python 是 Boost 的一个组件。而 Boost 是目前很红火的准 C++ 标准库,它提供了很多组件使得人们可以用 C++ 语言更方便地实现更多的功能。 Boost.Python 就是 Boost 众多组件中的一个。但它是个特例,它的目的不是单纯地增强 C++ 语言的功能,而是希望利用 C++ 语言来增强 Python 语言的能力。使用 Boost.Python 库,我可以方便地将 C++ 语言写的程序库用于 Python 语言,可以用 Python 更好地完成更多的任务。
相关文章推荐
- 使用C++创建Pyd文件扩展Python模块
- 扩展Python__在python脚本中使用其他语言(c/c++/java/c#)编写的模块
- Python 扩展使用 C/C++ 给 Python 写扩展模块的方法
- 使用C/C++代码编写Python模块
- c++开发python扩展模块:cannot open file ‘python25_d.lib’解决办法
- 使用 c++ 扩展python
- 使用c语言来扩展python模块
- 使用c++扩展python的功能
- 转)使用C/C++扩展Python
- VS2005使用distutils模块自动编译python扩展模块
- windows平台使用Microsoft Visual C++ Compiler for Python 2.7编译python扩展
- 使用Visual Studio.Net 2005开发Python扩展模块
- C++封装python扩展模块ImportError: No module named 原因分析
- 使用C/C++编写Python扩展库
- 使用 Boost.Python 嵌入 Python 模块到 C++
- 简单谈谈用c++扩展Python模块
- C++使用boost python import 其他路径的模块
- windows平台使用Microsoft Visual C++ Compiler for Python 2.7编译python扩展
- Distutils发布C++扩展的Python模块
- windows下使用mingw编译python扩展模块