[C++-SIG] design question - python extensions in C++

skaller skaller at maxtal.com.au
Sun Feb 6 15:10:18 CET 2000


Brad Venner wrote:
> 
> There are several design decisions now that I would like to get
> feedback on.  One problem I'm running into now is how to safely
> convert PyObject*'s to the appropriate and specific C++
> implementation.  

	Unfortunately, this is a necessary evil of object oriented
programming -- covariant typing requires a dynamic cast.

> PyObject* function(PyObject *self, PyObject* args) {
>   Tuple a(args);
>   // check length
>   PyObject* arg1 = a[0].ptr();
>   ObjectProtocol * arg1 = static_cast<ObjectProtocol*>(arg1);
>   if(arg1->check("MyObject")) {
>     MyObject * myob = static_cast<MyObject*>(arg1);
>     // do useful stuff
>   }
>   else throw TypeError("Function requires MyObject argument");
> }
> 
> Does anyone have a better idea or approach that I should consider.

	Why not just use a dyanamic cast?

	MyObject *o = dynamic_cast<MyObject *>(arg1);

This should work because the MyObject is derived from PyObject.
 
> A second problem is how to check for to see if a PyObject* implements
> a particular Python/C++ interface.  It would be nice to write C++
> functions that did not require conversion to a specific creation-type
> but instead could check to see if a creation-type implemented a
> particular interface, and then cast the PyObject* to a pointer to the
> interface.  Python checks for it's interface "types" (number,
> sequence, mapping) by checking for a null-pointer in the type object.
> A C++ equivalent is needed but I don't really see how to do it.

	This is tricky. One way is to further factor the abstraction
PyObject by making abstract bases PySequence and PyMapping.
Then (in theory) you can again use a dynamic cast:

	if (dynamic_cast<PySequence*>(object)) { .. a sequence .. }
	else { .. not a sequence .. }

-- 
John (Max) Skaller, mailto:skaller at maxtal.com.au
10/1 Toxteth Rd Glebe NSW 2037 Australia voice: 61-2-9660-0850
homepage: http://www.maxtal.com.au/~skaller
download: ftp://ftp.cs.usyd.edu/au/jskaller




More information about the Cplusplus-sig mailing list