利用Boost.Python将C++代码封装为Python模块

Boost.PythonC++代码封装为Python模块

一.     基础篇

借助Boost.Python库可以将C/C++代码方便、快捷地移植到python模块当中,实现对python模块的扩充。首先,将C++下的代码编译为动态库,并将生成的动态库命名为封装模块的名字,如:用BOOST_PYTHON_MODULE(Module_Name)宏对需要导出的函数、全局变量、类等导入Python的Module_Name模块,此时生成的动态库需要更名为Module_Name.pyd。然后,将Module_Name.pyd放在python的系统搜索目录中(通常是%PYTHON_PATH%\DLLs目录)。最后,在IDLE GUI界面或是python脚本中执行import Module_Name,这样就可以在python复用C++中定义的函数、类等而不必重写。

二.     实例篇

下面的实例代码主要针对抽象类、带默认实现虚函数的类、类的成员函数及操作符重载、带默认参数的函数(包括构造函数)、派生类、纯虚函数、返回对象及字符串的函数等的封装方法,基本概括了C+扩展到python模块的常见类型。

//boostpython_abs.h

#ifndefBOOSTPYTHON_ABS_H

#define BOOSTPYTHON_ABS_H

/*

*brief:

*  wrap c/c++ code as dll and export the class/function interfaces

*  to python as modules with boost-library

*author:

*  hank

*history:

*  created 2012-07-13

*/

#ifndef BSTPABS_API

    #define BSTPABS_API __declspec(dllimport)

#else

    #define BSTPABS_API __declspec(dllexport)

#endif

/*

1.export the abstract class into python module

2.abstract class with member over-load functions|operators

*/

class BSTPABS_API CPhone

{

public:

    enum Mode{ CANCONNET = 0, CONNECTED, PAUSE, DISCONNECTED };

public:

    CPhone(std::string owner = "" ){}

    virtual int make_call( int phone_num ) = 0;

    virtual std::string make_call( std::string name ) = 0;

    virtual CPhone& operator << ( int phone_num ) = 0;

    virtual CPhone& operator << ( std::string name ) = 0;

};

#endif//BOOSTPYTHON_ABS_H

//boostpython_abs.cpp

#include <boost/python.hpp>

#include "boostpython_abs.h"

//here,wrap the CPhone class

class CPhoneWrap :public CPhone,

                   public boost::python::wrapper<CPhone>

{

public:

    int make_call( int phone_num );

    std::string make_call( std::string name );

    CPhone& operator <<( int phone_num );

    CPhone& operator << ( std::string name );

};

//define function pointers of overload functions

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值