Boost.Python 的私有构造函数
Private constructor with Boost.Python
我正在尝试使用 Boost.Python.
将 C++ class 与私有构造函数绑定
假设我有以下 class:
class Test
{
public:
static Test& GetInstance()
{
static Test globalInstance;
return globalInstance;
}
int content(){return 0;}
private:
Test(){std::cout << "Object constructed" << std::endl;}
};
此 class 有一个私有构造函数,要获取 class 的实例,我们必须调用 GetInstance()
方法。
我尝试使用以下代码绑定它:
BOOST_PYTHON_MODULE(test)
{
class_<Test>("Test", no_init)
.def("create", &Test::GetInstance)
.def("content", &Test::content);
}
此代码无法编译并给出两个错误:
/Sources/Boost/boost/python/detail/invoke.hpp:75:12: error: type 'const boost::python::detail::specify_a_return_value_policy_to_wrap_functions_returning<Test &>' does not provide a call operator
/Sources/Boost/boost/python/detail/caller.hpp:102:98: error: no member named 'get_pytype' in 'boost::python::detail::specify_a_return_value_policy_to_wrap_functions_returning<Test &>'
但是,如果我创建一个调用 GetInstance()
的函数,如下所示:
Test create()
{
return Test::GetInstance();
}
并且我在绑定中将 .def("create", &Test::GetInstance)
替换为 .def("create", create)
,一切正常。
为什么我不能直接使用publicGetInstance()
方法?
这里的问题实际上是由于缺乏明确的return政策。如果 function/method 不按值 return,我们必须将其 return 策略设置为以下之一:
reference_existing_object
copy_non_const_reference
copy_const_reference
manage_new_object
return_by_value
所以,只需像这样绑定 GetInstance()
方法:
.def("create", &Test::GetInstance, return_value_policy<copy_non_const_reference>())
问题已解决。
希望它能对某人有所帮助,因为来自 Boost 的错误消息在这里帮助不大……
我正在尝试使用 Boost.Python.
将 C++ class 与私有构造函数绑定假设我有以下 class:
class Test
{
public:
static Test& GetInstance()
{
static Test globalInstance;
return globalInstance;
}
int content(){return 0;}
private:
Test(){std::cout << "Object constructed" << std::endl;}
};
此 class 有一个私有构造函数,要获取 class 的实例,我们必须调用 GetInstance()
方法。
我尝试使用以下代码绑定它:
BOOST_PYTHON_MODULE(test)
{
class_<Test>("Test", no_init)
.def("create", &Test::GetInstance)
.def("content", &Test::content);
}
此代码无法编译并给出两个错误:
/Sources/Boost/boost/python/detail/invoke.hpp:75:12: error: type 'const boost::python::detail::specify_a_return_value_policy_to_wrap_functions_returning<Test &>' does not provide a call operator
/Sources/Boost/boost/python/detail/caller.hpp:102:98: error: no member named 'get_pytype' in 'boost::python::detail::specify_a_return_value_policy_to_wrap_functions_returning<Test &>'
但是,如果我创建一个调用 GetInstance()
的函数,如下所示:
Test create()
{
return Test::GetInstance();
}
并且我在绑定中将 .def("create", &Test::GetInstance)
替换为 .def("create", create)
,一切正常。
为什么我不能直接使用publicGetInstance()
方法?
这里的问题实际上是由于缺乏明确的return政策。如果 function/method 不按值 return,我们必须将其 return 策略设置为以下之一:
reference_existing_object
copy_non_const_reference
copy_const_reference
manage_new_object
return_by_value
所以,只需像这样绑定 GetInstance()
方法:
.def("create", &Test::GetInstance, return_value_policy<copy_non_const_reference>())
问题已解决。
希望它能对某人有所帮助,因为来自 Boost 的错误消息在这里帮助不大……