我有以下(简化的)代码:
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/