【问题标题】:boost python wrappers for nested classes - restoring global scope为嵌套类提升 python 包装器 - 恢复全局范围
【发布时间】: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


    【解决方案1】:

    进入和退出范围仅由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::python nested namespace

    【讨论】:

      猜你喜欢
      • 2020-12-10
      • 1970-01-01
      • 2017-09-15
      • 2012-08-09
      • 1970-01-01
      • 2022-08-11
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      相关资源
      最近更新 更多