【发布时间】:2012-04-10 21:56:27
【问题描述】:
在the Boost Python documentation for "Header ", 描述了如何暴露一个类的子类。
但是,我找不到任何关于如何为多个类执行此操作的文档。 请参阅下面的代码,以文档中的代码为模型。如果我想写像
这样的代码w = nested.Z.W()
z.g()
等等。它不起作用,因为显然一旦范围被定义为 X,它就不会返回到全局范围。 因此,例如 Z 现在位于 X 的范围内。我怎样才能使其返回到全局范围?文档说
使用参数构造作用域对象会更改关联的 全局 Python 对象到参数所持有的对象,直到 范围对象的生命周期结束,此时关联的全局对象 Python 对象恢复到作用域对象之前的状态 构建。
更一般地说,这是有问题的,因为在构建此范围对象之后,我可能在模块中定义的对象会发生什么?它们最终都会在 X 的范围内吗?
解决此问题的一种方法是恢复全局范围。有谁知道如何做到这一点?任何其他解决此问题的方法也可以。
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/scope.hpp>
using namespace boost::python;
struct X
{
void f() {}
struct Y { int g() { return 42; } };
};
struct Z
{
void f() {}
struct W { int g() { return 91; } };
};
BOOST_PYTHON_MODULE(nested)
{
// add some constants to the current (module) scope
scope().attr("yes") = 1;
scope().attr("no") = 0;
// Change the current scope
scope outer
= class_<X>("X")
.def("f", &X::f)
;
// Define a class Y in the current scope, X
class_<X::Y>("Y")
.def("g", &X::Y::g)
;
// Change the current scope
// (this does not work as one would hope - W ends up inside Z, but Z is now in X.)
scope outer2
= class_<Z>("Z")
.def("f", &Z::f)
;
// Define a class Y in the current scope, X
class_<Z::W>("W")
.def("g", &Z::W::g)
;
}
【问题讨论】:
标签: c++ boost scope boost-python