Python 中的类成员函数必须显式声明一个表示类实例的 self
参数。有没有办法通过使用 Boost 从 C++ 获取 self
?
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
关于c++ - Boost.Python : Grab 'self' from member function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6878338/