将C ++创建的对象附加到python列表并使其由python管理

时间:2015-08-21 13:53:19

标签: list memory-management boost boost-python

好吧,我已经检查了一段时间,找不到答案。

我想追加一个暴露给python的对象,比如说Foo:

struct Foo {
  Foo(){ std::cout << "Creating a Foo object" << std::endl;}
  virtual ~Foo(){ std::cout << "Destroying a Foo object" << std::endl;}
};

我使用Foo继承的对象,并且在某些时候我想将它们附加到python列表。为此,我创建了一个FooWrapper,它继承自Foo并使用复制构造函数

struct FooWrapper : public Foo {
  FooWrapper(const Foo& foo):Foo(foo){ std::cout << "Creating a copy from foo using FooWrapper" << std::endl;}  
  virtual ~FooWrapper(){ std::cout << "Destroying a FooWrapper object" << std::endl;}
};

这是暴露给python:

BOOST_PYTHON_MODULE(foo_module)
{
    using namespace py = boost::python;
    py::class_<FooWrapper>("FooWrapper", py::no_init)…
}

我有一个方法将最终的Foo对象作为FooWrapper附加到python列表中,比如说:

void appendFoosToList(py::list &list)
{
  for ( const Foo* foo : m_foos )
  {
    list.append( FooWrapper( *foo )  );
  }
}                                                                                                                                 

我怎样才能这样做,而不是创建一个临时对象,然后复制到列表,我将该对象附加到列表中,而不必复制临时对象?

我读过很多文档(boost_faqboost_python_wiki),很多次我遇到this运行时错误:

  

TypeError:找不到C ++类型的to_python(by-value)转换器:   

     

BPL无法从Python对象获取C ++值。

     

例如,调用extract(.attr(“ len ”)())时   得到对象长度你省略了“()”。

并没有设法找到解决方案。

我找不到关于此的明确文档,所以我作为最后的手段来到这里。

1 个答案:

答案 0 :(得分:3)

简而言之,在免费商店中分配包装器并使用manage_new_object结果转换将所有权转移到Python对象。这将导致Boost.Python在构造Python对象时复制指针,而不是复制指针。

C ++对象嵌入到Python对象中。这是通过class_公开类时提供的HeldType,默认为公开的C ++类型。通常,在公开函数时,可以使用CallPolicy实例扩充返回并嵌入到Python对象中的C ++类型。特别是,使用return_value_policy CallPolicy和manage_new_object ResultConverterGenerator的实例允许嵌入类型作为指针,Python对象将管理所有权。

以下函数可用于将对象的所有权转移到Python,而无需复制指针对象:

/// @brief Transfer ownership to a Python object.  If the transfer fails,
///        then object will be destroyed and an exception is thrown.
template <typename T>
boost::python::object transfer_to_python(T* t)
{
  // Transfer ownership to a smart pointer, allowing for proper cleanup
  // incase Boost.Python throws.
  std::unique_ptr<T> ptr(t);

  // Use the manage_new_object generator to transfer ownership to Python.
  namespace python = boost::python;
  typename python::manage_new_object::apply<T*>::type converter;

  // Transfer ownership to the Python handler and release ownership
  // from C++.
  python::handle<> handle(converter(*ptr));
  ptr.release();

  return python::object(handle);
}

使用示例:

void appendFoosToList(boost::python::list& list)
{
  for (const Foo* foo : m_foos)
  {
    list.append(transfer_to_python(new FooWrapper(*foo)));
  }
}

这是一个完整的示例demonstrating这种方法:

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

// Mocks...
class spam
{
public:
  spam() { std::cout << "spam(): " << this << std::endl; }
  spam(const spam&)
  {
    std::cout << "spam(const spam&): " << this << std::endl;
  }
  ~spam() { std::cout << "~spam(): " << this << std::endl; }
};

/// @brief Transfer ownership to a Python object.  If the transfer fails,
///        then object will be destroyed and an exception is thrown.
template <typename T>
boost::python::object transfer_to_python(T* t)
{
  // Transfer ownership to a smart pointer, allowing for proper cleanup
  // incase Boost.Python throws.
  std::unique_ptr<T> ptr(t);

  // Use the manage_new_object generator to transfer ownership to Python.
  namespace python = boost::python;
  typename python::manage_new_object::apply<T*>::type converter;

  // Transfer ownership to the Python handler and release ownership
  // from C++.
  python::handle<> handle(converter(*ptr));
  ptr.release();

  return python::object(handle);
}

void append_to_list(boost::python::list& list)
{
  list.append(transfer_to_python(new spam()));
}

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<spam>("Spam", python::no_init);
  python::def("append_to_list", &append_to_list);
}

交互式使用:

>>> import example
>>> spams = []
>>> example.append_to_list(spams)
spam(): 0x25cbd90
>>> assert(type(spams[0]) is example.Spam)
>>> del spams
~spam(): 0x25cbd90