c++ - Boost.Python : Grab 'self' from member function

标签 c++ python boost

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/

相关文章:

c++ - 在 Qt 应用程序中使用自定义 dll

c++ - 使用 VideoCapture 读取目录中的图像不起作用

python - 如何使用 python/Django 更新 MySQL 中的多行(CASE、WHEN、THEN)

python - 是否有任何相当于 javascript 三重相等的 python 运算符?

c++ - 命名空间的 Boost.Log 错误

c++ - boost 上下文类

c++ - 对象 vector 的初始化

c++ - 获取辅助硬盘的空间 - C++

python - 修改给定 "path"的嵌套字典中的元素

boost - 如何自定义Boost.Log的 "TimeStamp"格式