增强嵌套类的 Python 包装器 - 恢复全局范围

boost python wrappers for nested classes - restoring global scope

本文关键字:恢复 全局 范围 包装 嵌套 Python 增强      更新时间:2023-10-16

在 Boost Python 文档中的 "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)
     ;
}

进入和退出作用域只是由scope对象的生存期处理(...另一种说法是:当相应的scope对象被破坏时,作用域结束)。在示例中,如果将"outer"scope括在大括号内,则"outer2"将(返回)在模块范围内。

BOOST_PYTHON_MODULE(nested)
{
  // add some constants to the current (module) scope
  scope().attr("yes") = 1;
  scope().attr("no") = 0;
  // Change the current scope
  { // -- limit C++ scope of outer
    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)
       ;
  } // -- finish scope "outer" --
  // Start new scope
  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)
     ;
}

这里有一个类似的答案:boost::p ython 嵌套命名空间