Cross-language class relationship

Gordon McMillan gmcm at hypernet.com
Wed May 19 10:41:26 EDT 1999


Alexander Staubo writes:

> Can a Python script's classes inherit from a class implemented by a
> C++ extension, and can a C++ extension's classes inherit (in some
> sense of the word) from a Python-implemented class?

Not in any straightforward (or even moderately convoluted) way.
 
> I know that SWIG supports "shadow classes" for C++ integration. I
> honestly haven't bothered to test how successfully the two
> integrate; since SWIG's shadow classes are ordinary Python classes,
> I assume it works pretty well. The question, though, is the ability
> for a C or C++ extension's classes to descend from ones implemented
> in Python.

Hmm, you've asked 2 questions here. They're quite different.

1) Class implemented in C++:

Python calls an extension through a C API
PyObject * <function>(PyObject *[, PyObject * [, ...]])

There's no opportunity to directly expose a C++ class's methods. SWIG 
can wrap stuff up, as long as you don't have any overloaded methods, 
and method args are vanilla (e.g., no C++ references). If you have a 
better conversion than the one SWIG generates, it's relatively easy 
to get SWIG to use yours. Shadow classes work well, though they mean 
you have to be careful about keeping stuff in synch. However, this is 
the easiest solution, because you don't have to write you C++ as an 
extension.

The next step up is to write an extension module that exposes new 
Python types. You've got a lot more rules to follow; it doesn't get 
you any closer to your goal (you can't override the type object's 
methods from Python), but you get direct exposure of your objects 
(and you can do your own shadow classes, ala UserDict etc.). The CXX 
package from LLNL lets you do your extension in C++ (if your compiler 
is sufficiently advanced).

The final step is sheer insanity - essentially you'd have to expose 
your type as an Instance type (or rather, something different but 
indistinguishable), which would allow Python to override it. This 
involves metaclasses and is virtually guaranteed to land you in a 
rubber room. If you're interested, pick up Extension Class from 
http://www.digicool.com/Free/.

As for question 2: No. A Python class is a completely dynamic thingy. 
It has only 2 "methods" that correspond to C++'s notion of "methods" 
- a constructor and a destructor - and those aren't even the ones you 
see from Python. You're stuck with something along the lines of 
"shadow classes" here. You can certainly obtain and use instances of 
Python classes from C/C++, but you're stictly a user. I think there 
are some patches someplace that let you directly bind a Python method 
to an extension module method, but that doesn't get you much closer 
to your goal.

C++-classes-are-from-the-moon--Python-classes-are-from-Sirius-ly y'rs


- Gordon




More information about the Python-list mailing list