Skip to content

Binding STL containers containing custom types #111

Answered by wjakob
nicholasjng asked this question in Q&A
Discussion options

You must be logged in to vote

You can simply include nanobind/stl/map.h and either bind your Foo type using nb::class_<> or implement a custom caster for it. This should be enough to get an automatic bidirectional conversion between the STL type and dict[str, Foo].

The main disadvantage of such an approach is performance when dealing with large maps. Every time you call a method that takes such a map as an input, all elements will be converted. Perhaps that's what you will need to do anyway, and then it does not matter. But if the function only accesses, say, 1 element in a map with millions of entries, then the py::bind_map approach from pybind11 will be superior.

There really isn't anything magic in py::bind_map tha…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@nicholasjng
Comment options

Answer selected by nicholasjng
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants