Boost.Python:从成员函数中获取'self'
Boost.Python: Grab 'self' from member function
Python中的类成员函数必须显式声明一个代表类实例的self
参数。是否有一种方法来获得self
从c++,通过使用Boost?
class FooBar
{
public:
void func() {
}
};
// A wrapper for the above class
struct FooBar_W
: public FooBar
{
void func(boost::python::object self) {
// Do smth with `self`
FooBar::func();
}
};
BOOST_PYTHON_WRAPPER(module)
{
class_<FooBar_W>("FooBar")
.def("func", &FooBar_W::func)
;
}
编辑:为什么我想要self
我正在为我的游戏编写一个事件系统,我希望脚本能够定义新的事件类型。我需要一种方法来区分不同类型的事件。我的Python代码看起来像这样:
class KeyboardEvent(Event):
pass
def onKeyPress(event):
pass
# EventManager is defined in C++
em = EventManager()
# This is how I register a new callback function with the manager
# The `onKeyPress` function will now only be notified when an event
# of type `KeyboardEvent` occurs. (Notice that I passed the actual
# class object, and not an instance of it.)
em.addEventHandler(KeyboardEvent, onKeyPress)
# This is how I queue new events
# (This time I pass an instance of an event, not a type of event.)
em.queueEvent(KeyboardEvent())
管理器需要知道我刚刚排队的是什么类型的事件。我想我应该做一些类似type(event).__name__
的事情(但在c++中,而不是在Python中)。这样我就可以确定类型并知道要通知哪些函数。我想在c++中获得self
,这样我就可以访问其类型的__name__
属性。
我可以让脚本程序手动编辑一个包含类型名称的新字段,但是为什么呢?该信息已经存在(__name__
属性),所以为什么要复制它,但更重要的是,为什么要用实现细节麻烦脚本程序呢?
这是可行的。方法可以在下面的链接中找到;该页记录了一种公开纯虚函数的方法(旧方法)。不过,这个例子可以适应其他需求。
> http://wiki.python.org/moin/boost.python/OverridableVirtualFunctions Pure_Virtual_Functions
这是一个老问题,但是对于那些仍然在寻找一个合理简单的解决方案的人:
静态函数(非成员和成员)接收const boost::python::object& self
作为第一个参数。所以你可以这样做:
class FooBar
{
public:
static void func(const boost::python::object self) {
FooBar& thisref = boost::python::extract<FooBar&>(self)();
// use self as well as thisref
}
};
};
BOOST_PYTHON_WRAPPER(module)
{
class_<FooBar>("FooBar")
.def("func", &FooBar::func)
;
}
python中的self
是c++中的this
。
您可以将FooBar::func();
行翻译为static_cast<FooBar*>(this)->func()
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 从C字符串中获取奇怪的字符串长度
- 为什么我的for循环不能正确获取argv
- 从python中调用C++函数并获取返回值
- 如何获取一个数字的前3位
- 获取字符串的长度并将其分配给数组
- 无法获取菜单选择以运行函数.C++
- 数组长度,为什么从命令行获取时不能使用它?
- Boost Spirit,获取迭代器内部语义动作
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 具有默认值的引用获取函数
- xmake总是报告:错误:无法获取cxx的程序,为什么
- Boost.Python:从成员函数中获取'self'