1

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?

1 Answer 1

2

If you dig through the macros you'll find PYBIND11_MODULE expands to a bit of code that is evaluated when your library is loaded from Python. For the rest your code looks like it should work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.