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

C++接口返回普通指針需要用參數(shù)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++中放棄對象所有權(quán)的另一種常見方式。這是通過將保持類型作為模板參數(shù)包含到class_<>來實現(xiàn)的,如下例所示:
#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()
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧
分享文章:C++boost::python普通指針和智能指針-創(chuàng)新互聯(lián)
路徑分享:http://www.chinadenli.net/article28/dodgcp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版、面包屑導(dǎo)航、搜索引擎優(yōu)化、網(wǎng)站制作、品牌網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)