GrecoDaVinci
GrecoDaVinci

Reputation: 111

How to define python pybind11 bindings of "operator()" C++ class method?

Say I have a simple C++ class

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

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

    private:
      int _value;
}

I am trying to create Python binding of this class using pybind11. How can I bind the operator() method?

This binding is going to be used to pass objects of this class to functions requiring a callback function as an argument.

Upvotes: 4

Views: 2432

Answers (1)

GrecoDaVinci
GrecoDaVinci

Reputation: 111

I figured this out after trying various things. We need to define the __call__ method in our binding. As an example:

.def("__call__", [](MyClass& this, AnotherClass& const b){
                   return this(b);
                 }
    )

Upvotes: 7

Related Questions