Can python control complicated classes/objects written in C++

Roger Binns rogerb at rogerbinns.com
Sat Jun 5 02:24:33 EDT 2004


Bo Peng wrote:
> I am planning on an application that involves several complicated C++
> classes. Basically, there will be one or two big data objects and some
> "action" objects that can act on the data. I would like to use a script
> language to control the interaction between these c++ objects.

The example you give will be no problem using SWIG and Python.

In general the area where things get tricky is dealing with
memory management.  You have to decide who "owns" any returned
objects - do they belong to the C++ code and have to be freed
via method calls, or do they belong to the Python proxy object
which frees them when it is deleted.

The former case can lead to memory leaks and the latter case
can lead to things being freed that are referenced by other
C++ objects.

You can have difficulty in this area if the underlying C++ library
is poorly designed.  For example I have had to deal with cases
where the C++ objects had references between each other and it
was really hard to figure out when to free the objects.  Mind you I
would encounter the same issues if using the library from other
C++ code.  In the end I had to write a C++ wrapper on top of the
C++ library and deal with reference counting and that kind of
stuff in the wrapper.  The wrapper trivially exported to Python
via SWIG.

I guess the point I am making in a long winded way is that if
the library is poorly designed, especially with respect to
objects ownership issues, then Python won't make them go away
and may highlight them more since more code paths become
possible.

Roger





More information about the Python-list mailing list