PyBind11: How to use a class as a data type

64 views Asked by At

How do I convert a C++ class into a 'data type', for instance, if I had a vector: dog_vector, I can convert it to a py::array and expose it to Python where it would be read as a Numpy array. How do I expose a class to Python, allowing for its methods to also be called from Python.

I am trying to create a callback function in Python which takes in a class defined in my C++ code i.e.

# Python side
import myextension

def make_dog_bark(dog: myextension.Dog):
    dog.bark()

How do I convert a class into a data type that can be used as such in Python? If Dog was a vector, for instance, my C++ binding for the callback would have been:

make_dog_bark(py::array_t<int64_t>(dog_vector.size(), dog_vector.data()))

and I would use in Python as

def make_dog_bark(dog_vector: npt.npt.NDArray):
    print(dog_vector)

I'm not sure if this is clear. I have tried to keep the example minimal and avoid putting all the callback registering and stuff but I can add more information if required.

0

There are 0 answers