我正在尝试使用 Boost.Python 将 C++ 类与私有(private)构造函数绑定(bind)。
假设我有以下类(class):
class Test
{
public:
static Test& GetInstance()
{
static Test globalInstance;
return globalInstance;
}
int content(){return 0;}
private:
Test(){std::cout << "Object constructed" << std::endl;}
};
这个类有一个私有(private)的构造函数,为了得到这个类的一个实例,我们必须调用 GetInstance()
方法。
我尝试使用以下代码绑定(bind)它:
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)
在我的绑定(bind)中,一切正常。
为什么我不能使用公共(public)GetInstance()
直接方法?
最佳答案
这里的问题实际上来自于缺乏明确的返回政策。如果函数/方法不按值返回,我们必须将其返回策略设置为以下之一:
reference_existing_object
copy_non_const_reference
copy_const_reference
管理新对象
返回值
因此,只需像这样绑定(bind) GetInstance()
方法:
.def("create", &Test::GetInstance, return_value_policy<copy_non_const_reference>())
解决问题。
希望它可以帮助到一些人,因为来自 Boost 的错误消息在这里没有太大帮助......
关于c++ - Boost.Python 的私有(private)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43733666/