Direct access to C++ containers from Python

In previous examples, I’ve shown how to pass Python lists into C++ using Boost.python. Because Python lists can contain a mixture of objects of different types, C++ has to use extract<type> to determine what kind of data to get from a list item. This approach works well, but it has its faults. In the C++ code, you might need to have duplicate data structures (a boost.python list to interchange data with Python and a C++ container such as a vector to process the data) and the code to convert between them. If you want to use your C++ library with languages other than Python, you want a non-Python-specific interface. Wouldn’t it be great to define your core data structures using a standard C++ container (like vector) and then access and modify them in Python?
You can, but it’s non-obvious and it’s not well explained in the Boost.python docs. Read the docs for the indexing suite and take a look at my demonstration code for exposing C++ vectors to Python, and you should be able to figure it out. Once you get it working, it’s a very clean way of doing things. Just remember, because you’re working with C++ containers that accept only the specified type of object Python will throw a TypeError if you try to append the wrong kind of object.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.