我想以正确的方式做这件事。我见过在Boost python export singleton中公开boost::serialization::singleton,但我不想使用它。我想使用简单的meyers单例。
下面的代码可以工作,但是文档显示使用http://www.boost.org/doc/libs/1_43_0/libs/python/doc/v2/reference_existing_object.html#reference_existing_object-spec/是危险的。
代码:
class Singleton
{
private:
Singleton(){};
public:
static Singleton & getInstance()
{
static Singleton instance;
return instance;
}
int getNumber() { return 5; }
};在模块中:
class_<Singleton>("singleton", no_init)
.def("getInstance", &Singleton::getInstance, return_value_policy<reference_existing_object>()).staticmethod("getInstance")
.def("getNumber", &Singleton::getNumber)
;做这件事的好方法是什么?使用return_internal_reference<>()会导致执行python代码时出错。
发布于 2012-09-07 21:50:15
我们的代码中有很多这样的东西,我没有想过一种简单的方法,但我们通过使用空删除器从引用中返回boost::shared_ptr<>来公开它们(我们以某种方式将代码的一部分移到了shared_ptr,而其他部分没有,所以这是一个混合体)。这不是最好的做法,但如果你确保在main离开后不对指针做任何事情,它就会像预期的那样工作,并且不会出现缺陷。
对象的生命周期将超过解释器的生命周期,所以在这里将任何引用传递回python时,您不必担心出现任何问题。这个库只有在解释器退出后才会被释放(可能会调用或不调用你的析构函数,有时可能会有一个整体,以防出现错误或其他情况)。因此,在本例中,您可以将解释器视为一个经典的main()函数。
class_<XY, shared_ptr<XY>, boost::noncopyable >("XY",no_init)
.def("getInstance",&XY::getSharedInstance )
.staticmethod("getInstance")
struct NullDeleter
{
void operator()(const void*){}
};
XY& XY::getInstance()
{
static XY in;
return in;
}
// This can also be written as a standalone function and added to the python class above.
shared_ptr<XY> XY::getSharedInstance()
{
return shared_ptr<XY>( &getInstance(), NullDeleter() );
}或者,您可以将sharedInstance非侵入式编写到一个单独的函数中,并在python包中使用:
shared_ptr<XY> getSharedInstance()
{
return shared_ptr<XY>( &XY::getInstance(), NullDeleter() );
}
class_<XY, shared_ptr<XY>, boost::noncopyable >("XY",no_init)
.def("getInstance",&getSharedInstance )
.staticmethod("getInstance")https://stackoverflow.com/questions/10738776
复制相似问题