【问题标题】:Private constructor with Boost.PythonBoost.Python 的私有构造函数
【发布时间】:2017-05-02 08:45:56
【问题描述】:

我正在尝试使用 Boost.Python 将 C++ 类与私有构造函数绑定。

假设我有以下课程:

class Test
{
    public:
        static Test& GetInstance()
        {
            static Test globalInstance;
            return globalInstance;
        }

        int content(){return 0;}

    private:
        Test(){std::cout << "Object constructed" << std::endl;}
};

这个类有一个私有构造函数,要获得这个类的实例,我们必须调用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&lt;Test &amp;&gt;' 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&lt;Test &amp;&gt;'

但是,如果我创建一个调用 GetInstance() 的函数,如下所示:

Test create()
{
    return Test::GetInstance();
}

并且我在绑定中将.def("create", &amp;Test::GetInstance) 替换为.def("create", create),一切正常。

为什么我不能直接使用 public GetInstance() 方法?

【问题讨论】:

    标签: c++ boost binding boost-python


    【解决方案1】:

    这里的问题实际上来自缺乏明确的退货政策。如果函数/方法不按值返回,我们必须将其返回策略设置为以下之一:

    • 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 的错误消息在这里没有太大帮助......

    【讨论】:

      猜你喜欢
      • 2011-04-20
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      相关资源
      最近更新 更多