如何定义“operator()”C++ 类方法的 python pybind11 绑定?

Gre*_*nci 3 c++ python callback pybind11

假设我有一个简单的 C++ 类

class MyClass{
     //constructor
     MyClass(int value):_value(value){};

     void operator()(AnotherClass& const b){
     // Do something with b object
     }

    private:
      int _value;
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用 pybind11 创建此类的 Python 绑定。如何绑定operator()方法?

此绑定将用于将此类的对象传递给需要回调函数作为参数的函数。

Gre*_*nci 6

在尝试了各种事情之后我发现了这一点。我们需要__call__在绑定中定义方法。举个例子:

.def("__call__", [](MyClass& this, AnotherClass& const b){
                   return this(b);
                 }
    )
Run Code Online (Sandbox Code Playgroud)