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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s