[C++-SIG] Python calling C++ issues

skaller skaller at maxtal.com.au
Thu Dec 2 15:18:29 CET 1999


Geoffrey Furnish wrote:
> The right thing to do, is to avoid efforts to cast function pointers.
> 
> For the Python/C++ interface, this basically means you need a seperate
> extension type object for each C++ object you wish to register as a
> Python extension.

	I don't believe this is the case. See below.
 
> Making this machinery work easily and maintainably seems to be
> challenging.  I don't personally have much hope for doing it, except
> through heavy use of template mechanisms, which have been the source
> of much consternation on this sig.

	I don't really understand this. It is very easy to do.
In some kind of minor simplification of python, exactly one abstract
base class is required. This class has a vtable (set of pure virtual
functions) which match the Python vtable.

	That's it: all extension type derive from this abstract
base, and they're all automatically valid python types.

	Now the gotcha: instead of a single linear vtable,
python has several subtables. The presence or absence of 
the subtable pointer (e.g the pointer to the sequence
subtable) has semantics. This complication may mean
some tricky design is needed; perhaps a minor
restriction of the extension type semantics 
(like: 'you can't be both a sequence and map').

	I will give an example, by taking
a tiny subset of the python virtual functions:
the len function, for example:

	class cpp_py_object {
	virtual int len() const = 0;
	...
	};


	Now, by using THIS class as the sole base
of all cpp extension types, you only need a single
CPython type, with a pointer to the C++ object
of type cpp_py_object.

	By FAR the most interesting aspect of this
is that you can dynamically load shared libraries
using dlopen (or windows equivalent), which have
factory functions in them which create extension types.

	These DLL's don't [necessarily] 
need to know anything about the Python wrapper objects which wrap them. 

-- 
John Skaller, mailto:skaller at maxtal.com.au
10/1 Toxteth Rd Glebe NSW 2037 Australia
homepage: http://www.maxtal.com.au/~skaller
voice: 61-2-9660-0850




More information about the Cplusplus-sig mailing list