BMI Students

Saturday, March 19, 2005

Writing python extensions in C++

I love Python. However, as of late, I have also come to understand why C++ can be a very useful language too. So I've been trying to find good ways of calling my C++ code from Python. The standard routes are to either use SWIG or write an extension in C.

SWIG is great and usually simple, but sometimes can feel too inflexible. Writing C extensions is super-flexible, but requires a lot of boilerplate code to do it correctly.

Today I found PyCXX, which is a set of C++ classes which work like C++ STL types, but proxy to Python objects. Now it's dead simple to integrate my C++ code with my Python code and have everything (a) work well, and (b) look nice.

Here's an example of manipulating a Python dictionary in Python:
d = {}
d["a"] = 1
d["b"] = 2
alist = d.keys()
print alist

And the same example in C++ with PyCXX:
Dict d;
List alist;
d["a"] = Int(1);
d["b"] = Int(2);
alist = d.keys();
std::cout << alist << std::endl;


Notice how easy it is to use Python objects in your C++ code?

0 Comments:

Post a Comment

<< Home