c++ - boost.python 暴露成员的成员

标签 c++ boost-python

我有以下(简化的)代码:

struct A
{
    int intVal;
    char charVal;
};

struct B
{
    A* someObj;
};

我想公开 B::A::intVal,但以下方法不起作用:

class_<B>("someClass")
    .def_readonly("var", &B::A::intVar)
    ;

我该怎么做?

最佳答案

B::A::intVar 不起作用,因为它是格式错误的合格 ID。我选择将问题分解为两部分:限定 ID 和在 Boost.Python 中公开成员中的成员。


以下代码将两个结构体引入同一个命名空间。因此,B::A 的 qualified-id 不存在,因为 B 不会将 A 重新引入为嵌套标识符:

struct A
{
  int intVal;
  char charVal;
};

struct B
{
  A* someObj;
};

要在 B 中引入 A 标识符,B 要么需要:

  • 包含A 结构的定义。 (即 A 成为嵌套结构)。

    struct B
    {
      struct A // introduces B::A
      {
        int intVal;
        char charVal;
      };
      A* someObj;
    };
    
  • A 提供 typedef。

    struct A
    {
      int intVal;
      char charVal;
    };
    
    struct B
    {
      typedef ::A A; // introduces B::A
      A* someObj;
    };
    

要直接公开成员中的成员,Boost.Python 将需要一个简单的辅助函数,例如:

/// @brief Helper function that returns B.someObj.intVal.
int get_b_intval(const B& self)
{
  return self.someObj->intVal;
}

辅助函数可以作为 Python B::var 只读属性公开。

namespace python = boost::python;
python::class_<B>("someClass")
  .add_property("var", &get_b_intval)
  ;

这是一个完整的例子:

#include <boost/python.hpp>

struct A
{
  int intVal;
  char charVal;
};

struct B
{
  A* someObj;
};


/// @brief Helper function that returns B.someObj.intVal.
int get_b_intval(const B& self)
{
  return self.someObj->intVal;
}

/// @brief Helper function to create a B object.
B make_B()
{
  static A a;
  a.intVal = 42;
  B b;
  b.someObj = &a;
  return b;
}

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<B>("someClass")
    .add_property("var", &get_b_intval)
    ;

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

及其用法:

>>> import example
>>> b = example.make_B()
>>> print b.var
42
>>> b.var = 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

关于c++ - boost.python 暴露成员的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17905935/

相关文章:

c++ - 如何制作 3des-cbc IV?

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

c++ - "Capture by move"不阻止引用捕获

c++ - 具有重复键的快速排序算法

c++ - qmap 可选参数的默认值

c++ - boost Python : polymorphic container?

c++ - 通过 Boost Python 在 C++ 对象之间传递共享指针的段错误

c++ - Linux Mint x64 : Qt 5. 3.1 插件部署:不兼容的 qt 库

c++ - 如何链接到现有的 boost python 模块

python - 将 Python 函数作为 Boost.Function 参数发送