由于Python自動處理內存分配和垃圾收集,因此“指針”的概念在Python中沒有意義。boost::python可以方便地處理C++普通指針和智能指針。

C++接口返回普通指針需要用參數return_value_policy
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普通指針和智能指針-創新互聯
路徑分享:http://www.yijiale78.com/article28/dodgcp.html
成都網站建設公司_創新互聯,為您提供網站改版、面包屑導航、搜索引擎優化、網站制作、品牌網站建設、網站導航
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯