C++boost::python普通指针和智能指针-创新互联

C++ boost::python 普通指针和智能指针
    • 普通指针(raw pointer)
    • 智能指针(Smart pointers)

由于Python自动处理内存分配和垃圾收集,因此“指针”的概念在Python中没有意义。boost::python可以方便地处理C++普通指针和智能指针。

创新互联专注于企业成都营销网站建设、网站重做改版、绿春网站定制设计、自适应品牌网站建设、H5开发商城网站建设、集团公司官网建设、成都外贸网站建设、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为绿春等各大城市提供网站开发制作服务。普通指针(raw pointer)

C++接口返回普通指针需要用参数return_value_policy(),python会对该对象自动垃圾回收(garbage collection)。

struct A {
    static A*   create () { return new A; }
    std::string hello  () { return "Hello, is there anybody in there?"; }
};

BOOST_PYTHON_MODULE(pointer)
{
    class_("A",no_init)
        .def("create",&A::create, return_value_policy())
        .staticmethod("create")
        .def("hello",&A::hello)
        ;
}

A sample python program:

from pointer import *
an_A = A.create()
print an_A.hello()
智能指针(Smart pointers)

使用智能指针(例如std::shared_ptr<T>)是在C++中放弃对象所有权的另一种常见方式。这是通过将保持类型作为模板参数包含到class_<>来实现的,如下例所示:

#include#include#includeusing namespace boost;
using namespace std;
using namespace boost::python;

struct A {
    static shared_ptr create () { return shared_ptr(new A); }
    std::string   hello  () { return "Just nod if you can hear me!"; }
};

BOOST_PYTHON_MODULE(shared_ptr)
{
    class_ >("A",init<>())
        .def("create",&A::create )
        .staticmethod("create")
        .def("hello",&A::hello)
    ;
}

也可以使用register_ptr_to_python将shared_ptr注册到python。

BOOST_PYTHON_MODULE(shared_ptr)
{
    class_("A",init<>())
        .def("create",&A::create )
        .staticmethod("create")
        .def("hello",&A::hello)
    ;
    register_ptr_to_python();
}

A sample python program:

from shared_ptr import *
an_A = A.create()
print an_A.hello()

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧

分享文章:C++boost::python普通指针和智能指针-创新互联
路径分享:https://www.cdcxhl.com/article28/dodgcp.html

成都网站建设公司_创新互联,为您提供网站改版面包屑导航搜索引擎优化网站制作品牌网站建设网站导航

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

h5响应式网站建设