Boost.Python:从成员函数中获取'self'

Boost.Python: Grab 'self' from member function

本文关键字:获取 self 函数 Python 成员 Boost      更新时间:2023-10-16

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()