1

"Header " の Boost Python ドキュメントでは、クラスのサブクラスを公開する方法が説明されています。

ただし、複数のクラスに対してこれを行う方法に関するドキュメントは見つかりませんでした。ドキュメントのコードをモデルにした以下のコードを参照してください。次のようなコードを書きたい場合

w = nested.Z.W()
z.g()

どうやらスコープがXに定義されると、グローバルスコープに戻らないため、機能しません。たとえば、Z は X のスコープ内に存在します。グローバル スコープに戻すにはどうすればよいですか? ドキュメントによると

引数を使用してスコープ オブジェクトを構築すると、スコープ オブジェクトの有効期間が終了するまで、関連付けられたグローバル Python オブジェクトが引数によって保持されるオブジェクトに変更されます。有効期間が終了すると、関連付けられたグローバル Python オブジェクトは、スコープ オブジェクトが構築される前の状態に戻ります。

より一般的に言えば、これは問題です。なぜなら、このスコープ オブジェクトの構築に続いて、モジュールで定義する可能性のあるオブジェクトはどうなるのですか?それらはすべて X のスコープに収まるでしょうか?

これを解決する 1 つの方法は、グローバル スコープを復元するメカニズムです。誰もこれを行う方法を知っていますか? これを解決する他の方法も問題ありません。

#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)
     ;
}
4

1 に答える 1

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 ネストされた名前空間

于 2012-10-25T01:11:50.170 に答える