zoukankan      html  css  js  c++  java
  • 使用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<T> 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<args...,
        policy2<args...,
            policy3<args...> > >

    以一个例子说明在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
    版权所有,欢迎转载
  • 相关阅读:
    RestTemplate方法总结
    服务器上获取不到header中设置的自定义的属性值
    记录一次 事务问题 的处理
    java 集合按照 数值排序,如果数值一致 按照名字首字母排序
    mysql中按照中文首字母A-Z排序
    java 关于小数 换算整数 的一点想法
    mysql 根据身份证查询 年龄 性别
    MySQL普通索引(BTREE索引)以及最左前缀匹配
    net.sf.json的常用api
    Object划分
  • 原文地址:https://www.cnblogs.com/xiaotie/p/351258.html
Copyright © 2011-2022 走看看