现在的位置: 首页 > 综合 > 正文

Python调用采用Boost Python封装的c++(2)

2013年09月05日 ⁄ 综合 ⁄ 共 1855字 ⁄ 字号 评论关闭

     上次我写了利用Python提供的API封装c函数,并调用。但是由于利用API的方式过于原始,对于类或者结构极度麻烦。因此,我选择了BoostPython的来封装类,类似的工具还有SWIG等,选择Boost的原因是它不需要引入其他的接口描述语言,封装也是c++代码;另外,它支持的c++特性比较全。

    Boost Python的文档,我推荐:http://www.maycode.com/boostdoc/boost-doc/libs/python/doc/。基本上,你遇到的问题,都可以找到答案。

   下面贴一个例子,这个例子覆盖的面很全,需要好好理解。这个例子,是研究怎么封装C++。下一节,我会写一些高级的用法。

  1. #include <boost/python.hpp>
  2. #include <boost/python/module.hpp>
  3. #include <boost/python/def.hpp>
  4. #include <boost/python/to_python_converter.hpp>
  5. #include
  6. using namespace std;
  7. using namespace boost::python;
  8. namespace HelloPython{
  9.   // 简单函数
  10.   char const* sayHello(){
  11.     return "Hello from boost::python";
  12.   }
  13.   // 简单类
  14.   class HelloClass{
  15.   public:
  16.     HelloClass(const string& name):name(name){
  17.     }
  18.   public:
  19.     string sayHello(){
  20.       return "Hello from HelloClass by : " + name;
  21.     }
  22.   private:
  23.     string name;
  24.   };
  25.   // 接受该类的简单函数
  26.   string sayHelloClass(HelloClass& hello){
  27.     return hello.sayHello() + " in function sayHelloClass";
  28.   }
  29.   //STL容器
  30.   typedef vector<int> ivector;
  31.   //有默认参数值的函数
  32.   void showPerson(string name,int age=30,string nationality="China"){
  33.     cout << name << " " << age << " " << nationality << endl;
  34.   }
  35.   // 封装带有默认参数值的函数
  36.   BOOST_PYTHON_FUNCTION_OVERLOADS(showPerson_overloads,showPerson,1,3) //1:最少参数个数,3最大参数个数
  37.   // 封装模块
  38.   BOOST_PYTHON_MODULE(HelloPython){
  39.     // 封装简单函数
  40.     def("sayHello",sayHello);
  41.     // 封装简单类,并定义__init__函数
  42.     class_("HelloClass",init())
  43.       .def("sayHello",&HelloClass::sayHello)//Add a regular member function
  44.       ;
  45.     def("sayHelloClass",sayHelloClass); // sayHelloClass can be made a member of module!!!
  46.     // STL的简单封装方法
  47.     class_("ivector")
  48.       .def(vector_indexing_suite());
  49.     class_ >("ivector_vector")
  50.       .def(vector_indexing_suite >());
  51.     // 带有默认参数值的封装方法
  52.     def("showPerson",showPerson,showPerson_overloads());
  53.   }

系列文章:
Python调用C/C++函数(1)
Python调用采用Boost Python封装的c++(2)
C++调用Python(3)
C++调用Python(4)
c++和Python互操作高级应用(5)         

抱歉!评论已关闭.