vendredi 30 octobre 2020

Programmatic bindings in pybind11

I am using pybind11 to export a library written in c++ as a python module. My situation is perhaps a little unusual in that the c++ library already contains structures with all of the metadata of the classes I want to export. I am considering whether I could make use of this existing metadata, rather than re-entering it all again to create the pybind11 bindings.

Normal pybind11 code might look something like this;

namespace py = pybind11;

PYBIND11_MODULE(pet, m) {
    py::class_<Pet>(m,"Pet")
            .def("feed", &Pet::feed, "Feed the pet")
            .def("walk", &Pet::walk, "Walk the pet");
}

I am considering doing something along these lines;

namespace py = pybind11;

PYBIND11_MODULE(pet, m) {
    py::class_<Pet> pet(m,"Pet");    
    for (int i = 0; i < pet_metadata.num_funcs; i++)
    {
        auto& md = pet_metadata.func[i];
        pet.def(md.name, md.fptr, md.descr);
    }
}

Are there any performance hits for doing something like this? I don't have a good understanding of how pybind11 works behind the scenes. Would the for loop run each time one of the bound functions is invoked from python? Or is it all being evaluated at compile time? Will this approach even work?

Aucun commentaire:

Enregistrer un commentaire