Boost.Python:如何公开std :: unique_ptr

mar*_*ipf 23 c++ python unique-ptr boost-python c++11

我对boost.python相当新,并尝试将函数的返回值公开给python.

函数签名如下所示:

 std::unique_ptr<Message> someFunc(const std::string &str) const;
Run Code Online (Sandbox Code Playgroud)

在python中调用函数时,我收到以下错误:

TypeError: No to_python (by-value) converter found for C++ type: std::unique_ptr<Message, std::default_delete<Message> >
Run Code Online (Sandbox Code Playgroud)

我在python中的函数调用如下所示:

a = mymodule.MyClass()
a.someFunc("some string here") # error here
Run Code Online (Sandbox Code Playgroud)

我试图暴露std :: unique_ptr但只是无法让它工作..有人知道如何正确暴露指针类?谢谢!

编辑: 我尝试了以下内容:

class_<std::unique_ptr<Message, std::default_delete<Message>>, bost::noncopyable ("Message", init<>())

;
Run Code Online (Sandbox Code Playgroud)

这个例子编译,但我仍然得到上面提到的错误.此外,我试图暴露类Message本身

class_<Message>("Message", init<unsigned>())

        .def(init<unsigned, unsigned>()) 
        .def("f", &Message::f)
;
Run Code Online (Sandbox Code Playgroud)

Tan*_*ury 16

简而言之,Boost.Python不支持move-semantics,因此不支持std::unique_ptr.Boost.Python的新闻/更改日志没有任何迹象表明它已针对C++ 11移动语义进行了更新.此外,此功能要求unique_ptr支持还未触碰了一年多.

然而,Boost.Python支持通过Python传递对象的独占所有权std::auto_ptr.由于unique_ptr本质上是一个更安全的版本auto_ptr,它应该是相当简单的使用,以适应一个API unique_ptr来使用的API auto_ptr:

  • 当C++将所有权转移到Python时,C++函数必须:
  • 当Python将所有权转移到C++时,C++函数必须:
    • 通过接受实例auto_ptr.在常见问题中提到的指针在C++返回一个manage_new_object将通过管理政策std::auto_ptr.
    • 对通道进行auto_ptr释放控制unique_ptrrelease()

给定一个无法更改的API /库:

/// @brief Mockup Spam class.
struct Spam;

/// @brief Mockup factory for Spam.
struct SpamFactory
{
  /// @brief Create Spam instances.
  std::unique_ptr<Spam> make(const std::string&);

  /// @brief Delete Spam instances.
  void consume(std::unique_ptr<Spam>);
};
Run Code Online (Sandbox Code Playgroud)

SpamFactory::make()SpamFactory::consume()需要经由辅助功能缠绕.

将所有权从C++转移到Python的功能通常可以由创建Python函数对象的函数包装:

/// @brief Adapter a member function that returns a unique_ptr to
///        a python function object that returns a raw pointer but
///        explicitly passes ownership to Python.
template <typename T,
          typename C,
          typename ...Args>
boost::python::object adapt_unique(std::unique_ptr<T> (C::*fn)(Args...))
{
  return boost::python::make_function(
      [fn](C& self, Args... args) { return (self.*fn)(args...).release(); },
      boost::python::return_value_policy<boost::python::manage_new_object>(),
      boost::mpl::vector<T*, C&, Args...>()
    );
}
Run Code Online (Sandbox Code Playgroud)

lambda委托给原始函数,并将releases()实例的所有权委托给Python,调用策略表明Python将取得lambda返回的值的所有权.在mpl::vector介绍了呼叫签名Boost.Python的,允许其妥善处理语言之间的函数调度.

结果adapt_unique暴露为SpamFactory.make():

boost::python::class_<SpamFactory>(...)
  .def("make", adapt_unique(&SpamFactory::make))
  // ...
  ;
Run Code Online (Sandbox Code Playgroud)

通用调整SpamFactory::consume()更难,但编写简单的辅助功能很容易:

/// @brief Wrapper function for SpamFactory::consume_spam().  This
///        is required because Boost.Python will pass a handle to the
///        Spam instance as an auto_ptr that needs to be converted to
///        convert to a unique_ptr.
void SpamFactory_consume(
  SpamFactory& self,
  std::auto_ptr<Spam> ptr) // Note auto_ptr provided by Boost.Python.
{
  return self.consume(std::unique_ptr<Spam>{ptr.release()});
}
Run Code Online (Sandbox Code Playgroud)

辅助函数委托给原始函数,并将auto_ptrBoost.Python提供的函数转换unique_ptr为API所需的函数.的SpamFactory_consume辅助函数被公开为SpamFactory.consume():

boost::python::class_<SpamFactory>(...)
  // ...
 .def("consume", &SpamFactory_consume)
 ;
Run Code Online (Sandbox Code Playgroud)

这是一个完整的代码示例:

#include <iostream>
#include <memory>
#include <boost/python.hpp>

/// @brief Mockup Spam class.
struct Spam
{
  Spam(std::size_t x) : x(x) { std::cout << "Spam()" << std::endl; }
  ~Spam() { std::cout << "~Spam()" << std::endl; }
  Spam(const Spam&) = delete;
  Spam& operator=(const Spam&) = delete;
  std::size_t x;
};

/// @brief Mockup factor for Spam.
struct SpamFactory
{
  /// @brief Create Spam instances.
  std::unique_ptr<Spam> make(const std::string& str)
  {
    return std::unique_ptr<Spam>{new Spam{str.size()}};
  }

  /// @brief Delete Spam instances.
  void consume(std::unique_ptr<Spam>) {}
};

/// @brief Adapter a non-member function that returns a unique_ptr to
///        a python function object that returns a raw pointer but
///        explicitly passes ownership to Python.
template <typename T,
          typename ...Args>
boost::python::object adapt_unique(std::unique_ptr<T> (*fn)(Args...))
{
  return boost::python::make_function(
      [fn](Args... args) { return fn(args...).release(); },
      boost::python::return_value_policy<boost::python::manage_new_object>(),
      boost::mpl::vector<T*, Args...>()
    );
}

/// @brief Adapter a member function that returns a unique_ptr to
///        a python function object that returns a raw pointer but
///        explicitly passes ownership to Python.
template <typename T,
          typename C,
          typename ...Args>
boost::python::object adapt_unique(std::unique_ptr<T> (C::*fn)(Args...))
{
  return boost::python::make_function(
      [fn](C& self, Args... args) { return (self.*fn)(args...).release(); },
      boost::python::return_value_policy<boost::python::manage_new_object>(),
      boost::mpl::vector<T*, C&, Args...>()
    );
}

/// @brief Wrapper function for SpamFactory::consume().  This
///        is required because Boost.Python will pass a handle to the
///        Spam instance as an auto_ptr that needs to be converted to
///        convert to a unique_ptr.
void SpamFactory_consume(
  SpamFactory& self,
  std::auto_ptr<Spam> ptr) // Note auto_ptr provided by Boost.Python.
{
  return self.consume(std::unique_ptr<Spam>{ptr.release()});
}

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<Spam, boost::noncopyable>(
      "Spam", python::init<std::size_t>())
    .def_readwrite("x", &Spam::x)
    ;

  python::class_<SpamFactory>("SpamFactory", python::init<>())
    .def("make", adapt_unique(&SpamFactory::make))
    .def("consume", &SpamFactory_consume)
    ;
}
Run Code Online (Sandbox Code Playgroud)

交互式Python:

>>> import example
>>> factory = example.SpamFactory()
>>> spam = factory.make("a" * 21)
Spam()
>>> spam.x
21
>>> spam.x *= 2
>>> spam.x
42
>>> factory.consume(spam)
~Spam()
>>> spam.x = 100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
    None.None(Spam, int)
did not match C++ signature:
    None(Spam {lvalue}, unsigned int)
Run Code Online (Sandbox Code Playgroud)