增强嵌套类的 Python 包装器 - 恢复全局范围
boost python wrappers for nested classes - restoring global scope
在 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 嵌套命名空间
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 当vector是tje全局变量时,c++中vector的内存管理
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何创建一个空的全局类并在启动时实例化它
- 内联函数中具有内部链接的全局变量
- 用C++将哈希表写入文件并从文件中恢复
- 为什么虚函数不能是静态的和全局的?
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 全局作用域中函数指针的赋值
- g++用户定义的动态链接库上的全局new和delete运算符
- 在命名空间中使用全局命名空间中的函数
- 全局变量 多读取器 一个写入器多线程安全?
- 类的全局对象和静态成员
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 不同作用域中的静态变量和全局变量
- 是否可以恢复到"default"全局命名空间?
- 全局范围 LPWSTR 在更改后恢复
- 增强嵌套类的 Python 包装器 - 恢复全局范围