[英]Boost.Python wrap raw pointer but expose methods
我有一個類,其中的方法可以獲取原始的指針:
struct Foo {
int getSomething() const { .. }
void setSomethingElse(int ) { .. }
// .. lots more getters, setters, and other methods ..
};
Foo* p = make_something();
我最初將其直接暴露給python:
py::class_<Foo, Foo*, boost::noncopyable>("Foo", py::no_init)
.def("getSomething", &Foo::getSomething)
// ..
;
但是我得到的Foo
來自積極地重用內存的分配器,而我在python中的使用可能會使這些Foo*
保持的時間比它們在C ++中實際存在的時間長。 所以我真的想包裝它們以節省一些值,例如:
struct FooWrapper {
Foo* p;
int val1;
FooWrapper(Foo* p) : p(p), val1(p->getVal1()) { }
operator Foo*() const { return p; }
int getVal1() const { return val1; }
};
FooWrapper fw(make_something());
但是現在為了使用健康的Foo
功能,我必須將一堆東西復制到FooWrapper
。 還是我?? 有沒有一種方法可以編寫和公開FooWrapper
,使得getVal1()
調用fw.getVal1()
但其他函數調用fw.p->getSomethingElse()
可以避免在Foo
上復制其他所有方法? 畢竟這是python,所以我猜我可以用getattr
做些什么?
這比我預期的要容易:
struct FooWrapper
{
// as before
static py::object getattr(py::object self, std::string attr)
{
FooWrapper& fw = py::extract<FooWrapper&>(self);
return py::getattr(py::object{py::ptr(fw.p)}, attr.c_str());
}
};
附:
py::class_<FooWrapper, boost::noncopyable>("Foo", py::no_init)
.def("getVal1", &FooWrapper::getVal1)
.def("getSomethingElse", &FooWrapper::getSomethingElse)
// ..
// and, finally, for everything else:
.def("__getattr__", &FooWrapper::getattr)
;
然后在python中:
>>> f = get_foo() # this is really a FooWrapper
>>> f.getVal1
<bound method FooWrapper.getVal1 of <Test.FooWrapper object at 0x7faacd8d48e8>>
>>> f.getVal2
<bound method Foo.getVal2 of <Test.Foo object at 0x7faacd8d6210>>
>>> f.getVal3
AttributeError: 'Foo' object has no attribute 'getV3'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.