[C++-sig] constructing aligned instance in python

VáclavŠmilauer eudoxos at arcig.cz
Mon Feb 13 11:07:18 CET 2012


> Hmm.  You might be able to make this work with another class that holds 
> the AlignedType and has an implicit conversion to it:

Nice trick, it surprisingly compiled.

I found meanwhile though that the problem is more general: whenever a new
instance of AlignedType is created from python, it will be possibly mis-aligned,
because the Python allocator does not care about alignment: it simply provides a
chunk of memory based on PyTypeObject.{tp_basicsize,tp_itemsize} for the type
being instantiated.

A possible workaround (though quite laborious) is to use the overloaded
operator new ot AlignedType, which aligns properly, and write all ctors
of the wrapped class such that pointer (manage_new_object, I assume?)
is returned:

  namespace py=boost::python;
  static AlignedType* AlignedType_new(){ return new AlignedType; }
  static AlignedType* AlignedType_copy(const AlignedType& other){
    return new AlignedType(other);
  }
  py::class_<AlignedType>("AlignedType",boost::python::no_init)
     .def("__init__",&AlignedType_new)
     .def("__init__",&AlignedType_copy)
  ;

Isn't that insane? Is there a better way?

Cheers, v.



More information about the Cplusplus-sig mailing list