转载自:http://blog.csdn.net/normallife/article/details/52556727 谢谢博主
Python很强大,但已有的模块可能满足不了人民日益增长的物质文化需求,于是有时需要编写扩展模块进行完善。
可行的方案有很多:SWIG、Weave、ctypes、BOOST……
BOOST无疑是开发最快的一种方案。下面介绍下最简单的C++ helloworld程序如何变为Python的一个模块。
1. 安装Python、Boost
这里用Linux环境。Python和Boost都用源码安装,网址为:
Python2.6: https://www.python.org
BOOST1.57.0: http://sourceforge.net/projects/boost/?source=typ_redirect
2. 编写helloworld.cpp
#define BOOST_PYTHON_SOURCE #include <boost/python.hpp> #include <iostream> using namespace std; using namespace boost::python; void hello_func() { cout<<"hello boost python"<<endl; } BOOST_PYTHON_MODULE(boostpy) { def("Hello", hello_func, "Function 's targets..."); }
3. 编译为动态库
命令行中执行:
g++ -shared -o boostpy.so -fPIC -I/YourPythonIncludePath/ helloworld.cpp -lpython2.6 -lboost_python
生成了动态链接库boostpy.so
4. Python环境中调用Hello
>>> import boostpy >>> boostpy.Hello() hello boost python >>>help(boostpy)Help on module boostpy: NAME boostpy FILE /...../boostpy.so FUNCTIONS Hello(...) Hello() -> None : Function 's targets... C++ signature : void Hello()
就是需要把C++封装成Python可以“理解”的类型。通过使用C++实现测试激励的内部逻辑,然后Python调用C++的这个实现函数即可,这样可以大大减轻脚本编写的速度以及复杂度。
转自:
http://www.aichengxu.com/view/2422100
http://www.open-open.com/lib/view/open1329532323890.html