首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用boost::python包装std::vector_indexing_suite

使用boost::python包装std::vector_indexing_suite
EN

Stack Overflow用户
提问于 2014-11-22 12:44:07
回答 2查看 7.9K关注 0票数 18

我正在使用C++绑定(使用boost:: Python )来处理一个库,它表示存储在文件中的数据。我的大多数半技术用户将使用Python与其交互,因此我需要尽可能地使用Python。但是,我也会让C++程序员使用该API,因此我不希望在C++方面妥协以适应Python绑定。

图书馆的很大一部分将由容器组成。为了使python用户更直观,我希望他们的行为类似于python列表,即:

代码语言:javascript
复制
# an example compound class
class Foo:
    def __init__( self, _val ):
        self.val = _val

# add it to a list
foo = Foo(0.0)
vect = []
vect.append(foo)

# change the value of the *original* instance
foo.val = 666.0
# which also changes the instance inside the container
print vect[0].val # outputs 666.0

测试设置

代码语言:javascript
复制
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <boost/python/register_ptr_to_python.hpp>
#include <boost/shared_ptr.hpp>

struct Foo {
    double val;

    Foo(double a) : val(a) {}
    bool operator == (const Foo& f) const { return val == f.val; }
};

/* insert the test module wrapping code here */

int main() {
    Py_Initialize();
    inittest();

    boost::python::object globals = boost::python::import("__main__").attr("__dict__");

    boost::python::exec(
        "import test\n"

        "foo = test.Foo(0.0)\n"         // make a new Foo instance
        "vect = test.FooVector()\n"     // make a new vector of Foos
        "vect.append(foo)\n"            // add the instance to the vector

        "foo.val = 666.0\n"             // assign a new value to the instance
                                        //   which should change the value in vector

        "print 'Foo =', foo.val\n"      // and print the results
        "print 'vector[0] =', vect[0].val\n",

        globals, globals
    );

    return 0;
}

shared_ptr的实现方式

使用shared_ptr,我可以获得与上面相同的行为,但这也意味着我必须使用共享指针来表示C++中的所有数据,从许多角度来看,这并不好。

代码语言:javascript
复制
BOOST_PYTHON_MODULE( test ) {
    // wrap Foo
    boost::python::class_< Foo, boost::shared_ptr<Foo> >("Foo", boost::python::init<double>())
        .def_readwrite("val", &Foo::val);

    // wrap vector of shared_ptr Foos
    boost::python::class_< std::vector < boost::shared_ptr<Foo> > >("FooVector")
        .def(boost::python::vector_indexing_suite<std::vector< boost::shared_ptr<Foo> >, true >());
}

在我的测试设置中,这将产生与纯Python相同的输出:

代码语言:javascript
复制
Foo = 666.0
vector[0] = 666.0

vector<Foo>的实现方式

直接使用向量在C++端提供了一个很好的干净设置。但是,结果与纯Python的行为方式不同。

代码语言:javascript
复制
BOOST_PYTHON_MODULE( test ) {
    // wrap Foo
    boost::python::class_< Foo >("Foo", boost::python::init<double>())
        .def_readwrite("val", &Foo::val);

    // wrap vector of Foos
    boost::python::class_< std::vector < Foo > >("FooVector")
        .def(boost::python::vector_indexing_suite<std::vector< Foo > >());
}

这就产生了:

代码语言:javascript
复制
Foo = 666.0
vector[0] = 0.0

这是“错误的”--更改原始实例并没有改变容器内的值。

我希望我不要太想要

有趣的是,无论我使用哪两个封装,这段代码都能工作:

代码语言:javascript
复制
footwo = vect[0]
footwo.val = 555.0
print vect[0].val

这意味着::python能够处理“假共享所有权”(通过其by_proxy返回机制)。在插入新元素的同时是否有实现相同目标的方法?

但是,如果答案是否定的,我想听听其他建议--在Python工具箱中,是否有一个类似的集合封装被实现,但它不作为python列表的例子?

非常感谢你读了这么多:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-03-01 23:23:44

由于语言之间的语义差异,当涉及集合时,通常很难在所有场景中应用单一的可重用解决方案。最大的问题是,虽然Python集合直接支持引用,但是C++集合需要一定程度的间接,例如具有shared_ptr元素类型。没有这个间接,C++集合将无法支持与Python集合相同的功能。例如,考虑引用同一个对象的两个索引:

代码语言:javascript
复制
s = Spam()
spams = []
spams.append(s)
spams.append(s)

如果没有类似指针的元素类型,C++集合就不能有两个引用同一个对象的索引。然而,根据使用和需求,可能有一些选项允许Python用户使用Pythonic-ish界面,同时仍然维护C++的单个实现。

  • 最重要的Pythonic解决方案是使用自定义转换器,将Pythonic对象转换为C++集合。有关实现细节,请参见答案。如果:,请考虑此选项
    • 这个系列的元素复制起来很便宜。
    • C++函数仅对rvalue类型(即std::vector<>const std::vector<>&)进行操作。这个限制阻止C++对Python集合或其元素进行更改。

  • 增强vector_indexing_suite功能,重用尽可能多的功能,例如用于安全处理索引删除和基础集合重新分配的代理:
    • 使用自定义HeldType公开模型,该模型充当智能指针,并委托给从vector_indexing_suite返回的实例或元素代理对象。
    • 猴补丁将元素插入集合的集合方法,以便将自定义HeldType设置为委托给元素代理。

当向Boost.Python公开类时,HeldType是嵌入到Boost.Python对象中的对象类型。当访问包装类型对象时,Boost.Python为HeldType调用get_pointer()。下面的object_holder类提供了将句柄返回给它拥有的实例或元素代理的能力:

代码语言:javascript
复制
/// @brief smart pointer type that will delegate to a python
///        object if one is set.
template <typename T>
class object_holder
{
public:

  typedef T element_type;

  object_holder(element_type* ptr)
    : ptr_(ptr),
      object_()
  {}

  element_type* get() const
  {
    if (!object_.is_none())
    {
      return boost::python::extract<element_type*>(object_)();
    }
    return ptr_ ? ptr_.get() : NULL;
  }

  void reset(boost::python::object object)
  {
    // Verify the object holds the expected element.
    boost::python::extract<element_type*> extractor(object_);
    if (!extractor.check()) return;

    object_ = object;
    ptr_.reset();
  }

private:
  boost::shared_ptr<element_type> ptr_;
  boost::python::object object_;
};

/// @brief Helper function used to extract the pointed to object from
///        an object_holder.  Boost.Python will use this through ADL.
template <typename T>
T* get_pointer(const object_holder<T>& holder)
{
  return holder.get();
}

在间接支持的情况下,唯一剩下的就是修补集合以设置object_holder。支持这一点的一种干净和可重用的方法是使用def_visitor。这是一个通用接口,允许非侵入性地扩展class_对象。例如,vector_indexing_suite使用此功能。

猴子下面的custom_vector_indexing_suite类将append()方法修补为委托给原始方法,然后使用代理调用新集合元素的object_holder.reset()。这将导致引用集合中包含的元素的object_holder

代码语言:javascript
复制
/// @brief Indexing suite that will resets the element's HeldType to
///        that of the proxy during element insertion.
template <typename Container,
          typename HeldType>
class custom_vector_indexing_suite
  : public boost::python::def_visitor<
      custom_vector_indexing_suite<Container, HeldType>>
{
private:

  friend class boost::python::def_visitor_access;

  template <typename ClassT>
  void visit(ClassT& cls) const
  {
    // Define vector indexing support.
    cls.def(boost::python::vector_indexing_suite<Container>());

    // Monkey patch element setters with custom functions that
    // delegate to the original implementation then obtain a 
    // handle to the proxy.
    cls
      .def("append", make_append_wrapper(cls.attr("append")))
      // repeat for __setitem__ (slice and non-slice) and extend
      ;
  }

  /// @brief Returned a patched 'append' function.
  static boost::python::object make_append_wrapper(
    boost::python::object original_fn)
  {
    namespace python = boost::python;
    return python::make_function([original_fn](
          python::object self,
          HeldType& value)
        {
          // Copy into the collection.
          original_fn(self, value.get());
          // Reset handle to delegate to a proxy for the newly copied element.
          value.reset(self[-1]);
        },
      // Call policies.
      python::default_call_policies(),
      // Describe the signature.
      boost::mpl::vector<
        void,           // return
        python::object, // self (collection)
        HeldType>()     // value
      );
  }
};

包装需要在运行时进行,并且不能通过def()直接在类上定义自定义函式对象,因此必须使用make_function()函数。对于函子,它需要CallPolicies和表示签名的MPL前可扩展序列

下面是一个完整的示例,演示使用object_holder将代理委托给代理,使用custom_vector_indexing_suite对集合进行修补。

代码语言:javascript
复制
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

/// @brief Mockup type.
struct spam
{
  int val;

  spam(int val) : val(val) {}
  bool operator==(const spam& rhs) { return val == rhs.val; }
};

/// @brief Mockup function that operations on a collection of spam instances.
void modify_spams(std::vector<spam>& spams)
{
  for (auto& spam : spams)
    spam.val *= 2;
}

/// @brief smart pointer type that will delegate to a python
///        object if one is set.
template <typename T>
class object_holder
{
public:

  typedef T element_type;

  object_holder(element_type* ptr)
    : ptr_(ptr),
      object_()
  {}

  element_type* get() const
  {
    if (!object_.is_none())
    {
      return boost::python::extract<element_type*>(object_)();
    }
    return ptr_ ? ptr_.get() : NULL;
  }

  void reset(boost::python::object object)
  {
    // Verify the object holds the expected element.
    boost::python::extract<element_type*> extractor(object_);
    if (!extractor.check()) return;

    object_ = object;
    ptr_.reset();
  }

private:
  boost::shared_ptr<element_type> ptr_;
  boost::python::object object_;
};

/// @brief Helper function used to extract the pointed to object from
///        an object_holder.  Boost.Python will use this through ADL.
template <typename T>
T* get_pointer(const object_holder<T>& holder)
{
  return holder.get();
}

/// @brief Indexing suite that will resets the element's HeldType to
///        that of the proxy during element insertion.
template <typename Container,
          typename HeldType>
class custom_vector_indexing_suite
  : public boost::python::def_visitor<
      custom_vector_indexing_suite<Container, HeldType>>
{
private:

  friend class boost::python::def_visitor_access;

  template <typename ClassT>
  void visit(ClassT& cls) const
  {
    // Define vector indexing support.
    cls.def(boost::python::vector_indexing_suite<Container>());

    // Monkey patch element setters with custom functions that
    // delegate to the original implementation then obtain a 
    // handle to the proxy.
    cls
      .def("append", make_append_wrapper(cls.attr("append")))
      // repeat for __setitem__ (slice and non-slice) and extend
      ;
  }

  /// @brief Returned a patched 'append' function.
  static boost::python::object make_append_wrapper(
    boost::python::object original_fn)
  {
    namespace python = boost::python;
    return python::make_function([original_fn](
          python::object self,
          HeldType& value)
        {
          // Copy into the collection.
          original_fn(self, value.get());
          // Reset handle to delegate to a proxy for the newly copied element.
          value.reset(self[-1]);
        },
      // Call policies.
      python::default_call_policies(),
      // Describe the signature.
      boost::mpl::vector<
        void,           // return
        python::object, // self (collection)
        HeldType>()     // value
      );
  }

  // .. make_setitem_wrapper
  // .. make_extend_wrapper
};

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;

  // Expose spam.  Use a custom holder to allow for transparent delegation
  // to different instances.
  python::class_<spam, object_holder<spam>>("Spam", python::init<int>())
    .def_readwrite("val", &spam::val)
    ;

  // Expose a vector of spam.
  python::class_<std::vector<spam>>("SpamVector")
    .def(custom_vector_indexing_suite<
      std::vector<spam>, object_holder<spam>>())
    ;

  python::def("modify_spams", &modify_spams);
}

互动用法:

代码语言:javascript
复制
>>> import example
>>> spam = example.Spam(5)
>>> spams = example.SpamVector()
>>> spams.append(spam)
>>> assert(spams[0].val == 5)
>>> spam.val = 21
>>> assert(spams[0].val == 21)
>>> example.modify_spams(spams)
>>> assert(spam.val == 42)
>>> spams.append(spam)
>>> spam.val = 100
>>> assert(spams[1].val == 100)
>>> assert(spams[0].val == 42) # The container does not provide indirection.

由于vector_indexing_suite仍在使用中,因此底层C++容器只能使用Python的API进行修改。例如,调用容器上的push_back可能会导致底层内存的重新分配,并导致现有的Boost.Python代理出现问题。另一方面,可以安全地修改元素本身,就像通过上面的modify_spams()函数所做的那样。

票数 4
EN

Stack Overflow用户

发布于 2014-12-02 23:01:56

不幸的是,答案是不,你不能做你想做的事。在python中,一切都是指针,列表是指针的容器。共享指针的C++向量可以工作,因为底层数据结构或多或少等同于python。您所要求的是让分配内存的C++向量像指针向量一样工作,这是无法完成的。

让我们看看python列表中发生了什么,使用了C++等效的伪代码:

代码语言:javascript
复制
foo = Foo(0.0)     # Foo* foo = new Foo(0.0)
vect = []          # std::vector<Foo*> vect
vect.append(foo)   # vect.push_back(foo)

此时,foovect[0]都指向相同的分配内存,因此更改*foo会更改*vect[0]

现在使用vector<Foo>版本:

代码语言:javascript
复制
foo = Foo(0.0)      # Foo* foo = new Foo(0.0)
vect = FooVector()  # std::vector<Foo> vect
vect.append(foo)    # vect.push_back(*foo)

在这里,vect[0]有自己分配的内存,并且是*foo的副本。从根本上说,你不能让vect成为与*foo相同的内存。

另外,在使用footwo时,要小心std::vector<Foo>的生命周期管理。

代码语言:javascript
复制
footwo = vect[0]    # Foo* footwo = &vect[0]

后续追加可能需要移动为向量分配的存储空间,并可能使footwo无效(&vect可能会更改)。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27077518

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档