利用C++ Boost编写扩展Python模块

来源:互联网 发布:欧洲30年战争知乎 编辑:程序博客网 时间:2024/05/18 02:38
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    boostpyFILE    /...../boostpy.soFUNCTIONS    Hello(...)        Hello() -> None :            Function 's targets...            C++ signature :                void Hello()
就是需要把C++封装成Python可以“理解”的类型。通过使用C++实现测试激励的内部逻辑,然后Python调用C++的这个实现函数即可,这样可以大大减轻脚本编写的速度以及复杂度。
#include <boost/python.hpp> #include <boost/python/module.hpp> #include <boost/python/def.hpp> #include <boost/python/to_python_converter.hpp> #include using namespace std; using namespace boost::python;namespace HelloPython{ // 简单函数 char const* sayHello(){     return "Hello from boost::python"; }// 简单类 class HelloClass{ public:     HelloClass(const string& name):name(name){     } public:     string sayHello(){       return "Hello from HelloClass by : " + name;     } private:     string name; }; // 接受该类的简单函数 string sayHelloClass(HelloClass& hello){     return hello.sayHello() + " in function sayHelloClass"; }//STL容器 typedef vector<int> ivector;//有默认参数值的函数 void showPerson(string name,int age=30,string nationality="China"){     cout << name << " " << age << " " << nationality << endl; }// 封装带有默认参数值的函数 BOOST_PYTHON_FUNCTION_OVERLOADS(showPerson_overloads,showPerson,1,3) //1:最少参数个数,3最大参数个数// 封装模块 BOOST_PYTHON_MODULE(HelloPython){     // 封装简单函数     def("sayHello",sayHello);    // 封装简单类,并定义__init__函数     class_("HelloClass",init())       .def("sayHello",&HelloClass::sayHello)//Add a regular member function       ;     def("sayHelloClass",sayHelloClass); // sayHelloClass can be made a member of module!!!    // STL的简单封装方法     class_("ivector")       .def(vector_indexing_suite());     class_ >("ivector_vector")       .def(vector_indexing_suite >());    // 带有默认参数值的封装方法     def("showPerson",showPerson,showPerson_overloads()); }

转自:
http://www.aichengxu.com/view/2422100
http://www.open-open.com/lib/view/open1329532323890.html
0 0