On May 7, 2009, at 2:56 AM, Dag Sverre Seljebotn wrote:

>> Yes, you can, we do that in Sage. I don't think one can declare a
>> struct member to be an object without a no-args constructor without
>> extra work though, so one would have to do the same hackery that was
>> proposed for stack-allocated objects.
>
> I don't know enough CPython, but another (cleaner) option could be to
> allocate the whole PyObject using C++ new (which would pass on the
> constructor arguments to the field using the "MyClass(int arg) :
> myfield(arg) {}" syntax), and override tp_alloc to return that  
> object? If
> it is possible to tell tp_alloc about that somehow.

PyObject *tp_alloc(PyTypeObject *self, int nitems)

I wouldn't call it cleaner, but one could have tp_alloc/tp_new raise  
an error, and then always construct the objects manually. Feels like  
we're abusing something there.

> Another idea BTW is that we can use C++ templates to generate these  
> Python
> wrappers, so we only need to output one (manually written) template  
> to our
> code, and can then use
>
> CppPyWrapper<mymod::MyCppClass, "mymod::MyCppClass">
>
> and it could instantiate the right type structure through more  
> template
> programming etc.

One would have to have

struct CppPyWrapper {
     PyObject_HEAD
     MyCppClass;
     CppPyWrapper() : MyCppClass(default_args) { };
};

which is no better than simply trying to put MyCppClass on the stack,  
so sticking the memory chunk in a PyObject* doesn't really save you  
anything. (Well, it lets you pass it out of the scope, and gives  
reference assignment semantics, but I'm not sure either of these are  
desirable for something that looks like its allocated on the stack,  
and one could provide this in an orthogonal way (e.g. with the  
"managed" keyword idea). Also, giving it reference semantics means  
that we could never go and optimize it by placing things actually on  
the stack.

- Robert

_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to