python wrapper_使用pyste自动生成c++类的python wrapper

pyste是boost.python自带的代码生成器,利用pyste可以很方便的为c++ 的

lib加一层python的shell。如果当前boost版本不支持pyste的话,可以到boost官方网站上下载最新版本的boost源码。以

boost 1.3.1为例,进入boost_1_33_1/libs/python/pyste/install目录,运行python

setup.py install,安装pyste。

安装完pyste后还不能直接用,因为pyste依赖gccxml,所以需要安装gccxml。最好从源码make。直接安装二进制我没安装成功。如果

gcc环境是gcc4.*,需要从cvs下载最新的gccxml。gcc

xml采用cmake控制,没cmake的最好安装cmake(从源码make,最好不要安装二进制的)。

pyste使用模式推荐如下:

写一个配置文件My.pyste,上面写好类的映射项,如

Class("A", "A.h")

代表将A.h中的c++类A的public成员映射为python中的类A的相关成员

python -I/usr/include/python2.4 -I...... --module=MyModule My.pyste

将会自动生成一个wrapper的cpp程序。编译链接这个程序及其依赖项为MyModule.so,就可以直接在python中使用类A了。

需要注意的是,如果A中某些public 方法参数或返回值是指针或引用,因为pyste不能判断其生命周期,因此不能正确的转换,会报错误。此时,需要对这个方法加上一些策略约束。

常用策略有:

# with_custodian_and_ward

Ties lifetimes of the arguments

# with_custodian_and_ward_postcall

Ties lifetimes of the arguments and results

# return_internal_reference

Ties lifetime of one argument to that of result

# return_value_policy with T one of:

# reference_existing_object

naive (dangerous) approach

# copy_const_reference

Boost.Python v1 approach

# copy_non_const_reference

# manage_new_object

Adopt a pointer and hold the instance

具体的解释和使用方法见:

http://www.boost.org/libs/python/doc/tutorial/doc/html/python/functions.html#python.call_policies

策略可以嵌套,如

policy1

policy2

policy3 > >

以一个例子说明在pyste配置文件中如何使用方法的策略:

假定类B中有一个方法:

A* B::Method1()

{

......

}

A*是B管理的一个对象,其生命周期由B控制。

那么pyste策略应该写为:

CLASS_B = Class("B", "B.h")

set_policy(CLASS_B.Method1,return_value_policy(reference_existing_object))

注意,Boost.Python中的策略用模板格式< , >>表示,在pyste中,用()格式表示:( , (, (, ... )))。

更详细的内容还是请看Boost.Python的文档及pyste的文档吧。

Boost.Python文档:

http://www.boost.org/libs/python/doc/tutorial/doc/html/index.html

pyste文档:

http://www.boost.org/libs/python/pyste/index.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值