Skip to content

Instantly share code, notes, and snippets.

@MatteoRagni
Created December 5, 2019 21:02
Show Gist options
  • Save MatteoRagni/bd8d1658d430503c16511d41e278a7a7 to your computer and use it in GitHub Desktop.
Save MatteoRagni/bd8d1658d430503c16511d41e278a7a7 to your computer and use it in GitHub Desktop.
Pybind11 inheritance from a virtual class with different signature methods
#include "pybind11/pybind11.h"
#include <tuple>
namespace py = pybind11;
// Begin Library
class Animal {
public:
virtual ~Animal() { }
virtual int go(int a, int & b) = 0;
};
class Dog : public Animal {
public:
int go(int a, int & b) override {
b = a * 2;
return b * 2;
}
};
class Cat : public Animal {
public:
int go(int a, int & b) override {
b = a * 3;
return b * 3;
}
};
// End Library
class PyAnimal : public Animal {
public:
/* Inherit the constructors */
using Animal::Animal;
int go(int a, int & b) override {
PYBIND11_OVERLOAD_PURE(
int, /* Return type */
Animal, /* Parent class */
go, /* Name of function in C++ (must match Python name) */
a, b /* Argument(s) */
);
}
};
PYBIND11_MODULE(Animal, m) {
py::class_<Animal, PyAnimal>(m, "Animal")
.def(py::init<>())
.def("go", [](Animal * self, int a) {
int b, c;
c = self->go(a, b);
return std::make_tuple(b, c);
});
py::class_<Dog, Animal>(m, "Dog")
.def(py::init<>());
py::class_<Cat, Animal>(m, "Cat")
.def(py::init<>());
}
import Animal
a = Animal.Dog()
print(a)
print(a.go(10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment