0

我想实现和使用一些类Base。在 Python 中是这样的:

class Base:
    def Enumerate(self):
        d = []
        for attr in dir(self):
            if not attr.startswith('__') and not callable(getattr(self, attr)):
                d.append(attr)
        return d

class One(Base):
    hello = "world"

class Two(Base):
    foo = "bar"

arr = [One(), Two()]

arr[0].Enumerate()
arr[1].Enumerate()

但我想Base在 C++ 中使用boost::python.

我用谷歌搜索了很多,但没有找到任何东西。看起来与boost::python::wrapper.

有人可以指出我如何做到这一点吗?

4

1 回答 1

2

如果您不熟悉 Boost.Python,那么本教程是一个不错的起点。除此之外,参考是一个很好的资源,但需要一些经验,并且可能有点吓人或深奥。此外,Boost.Python 并没有为整个Python/C API提供方便的函数,需要开发人员偶尔直接对 Python/C API 进行编码。

这是一个完整的 Boost.Python 示例,注释中注明了 Python 代码:

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

/// @brief dir() support for Boost.Python objects.
boost::python::object dir(boost::python::object object)
{
  namespace python = boost::python;
  python::handle<> handle(PyObject_Dir(object.ptr()));
  return python::object(handle);
}

/// @brief callable() support for Boost.Python objects.
bool callable(boost::python::object object)
{
  return 1 == PyCallable_Check(object.ptr());
}

class base {};

/// @brief Returns list of an object's non-special and non-callable
///        attributes.
boost::python::list enumerate(boost::python::object object)
{
  namespace python = boost::python;
  python::list attributes; // d = []

  typedef python::stl_input_iterator<python::str> iterator_type;
  for (iterator_type name(dir(object)), end; // for attr in dir(self):
       name != end; ++name)
  {
    if (!name->startswith("__")           // not attr.startswith('__')
        && !callable(object.attr(*name))) // not callable(getattr(self, attr))
      attributes.append(*name);           // d.append(attr)
  }

  return attributes; // return d
}

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<base>("Base")
    .def("Enumerate", &enumerate)
    ;
}

及其用法:

>>> from example import Base
>>> 
>>> class One(Base):
...     hello = "world"
... 
>>> class Two(Base):
...     foo = "bar"
... 
>>> arr = [One(), Two()]
>>> 
>>> arr[0].Enumerate()
['hello']
>>> arr[1].Enumerate()
['foo']

尽管 Boost.Python 在提供 Python 和 C++ 之间的无缝互操作性方面做得很好,但如果可能,请考虑用 Python 而不是 C++ 编写 Python。虽然这是一个简单的示例,但使用 C++ 编写的程序几乎没有收获。在更广泛的示例中,它可能很快需要关注非常微小的细节,这对保持 Python 风格提出了一个有趣的挑战。

于 2013-09-17T18:23:26.160 回答