AW: [C++-sig] Wrapping opaque pointers returned from API function s

David Abrahams dave at boost-consulting.com
Mon Jan 13 13:46:43 CET 2003


Gottfried.Ganssauge at HAUFE.DE writes:

>> I didn't say I tested the code ;-)
>
> Of course.
> Anyway, your upcast is probably invalid anyway, because PyObject ist not a
> base class of instance.

No, it is not invalid.  My upcast template is specially designed to
deal with this.  Please try doing as I suggested.

>> No, that's non-POD.  It has a base class.  
>
> I think I have a solution that is hopefully more conforming but doesn't rely
> on the Python implementation details (and it even resembles a bit to real
> inheritance)
> 	struct instance {
> 		PyObject base_;
> 		Pointer x;
> 	};

The contents of PyObject are still Python implementation details.
This one is no better than my proposal, and may in fact take extra
storage for alignment.

> 	static PyObject* convert(Pointer x)
> 	{
> 		instance *o = PyObject_New (instance, &type_object);
> 		o->x = x;
> 		return &o->base_;
> 	}
> I can't lookup the paragraph in the standard, but I found something in the
> draft of "C++ in a nutshell".
> In Chapter 7 it says:
> """
> A POD class can contain padding between data members, but no padding appears
> before the first member. Therefore, a pointer to the POD object can be
> converted (with reinterpret_cast<>) to a pointer to the first element.
> """

They're wrong about reinterpret_cast<>, as far as the standard goes.
That performs an implementation-defined mapping.  The only thing you
can do portably with it is convert a pointer to a different type and
back again, without using it in between.  Please, just try it the way
I suggested!

-- 
                       David Abrahams
   dave at boost-consulting.com * http://www.boost-consulting.com
Boost support, enhancements, training, and commercial distribution





More information about the Cplusplus-sig mailing list