Robert wrote:
> On May 7, 2009, at 2:14 AM, Stefan Behnel wrote:
>
>> Dag Sverre Seljebotn wrote:
>>>> Dag Sverre Seljebotn wrote:
>>>>> Allocation would happen through an actual (as light-weight as
>>>>> possible, and probably mostly opaque, perhaps doing as much as
>>>>> printing
>>>>> the C++ name of the class in its repr) Python object
>>>>
>>>> That wouldn't work, though. Imagine you'd return the C++ object
>>>> pointer
>>>> from a function. What would happen to the Python object that
>>>> holds it?
>>>> How would you keep the ref-counting context for it?
>>>
>>> There would be no coercion between pointers and refcounted
>>> variables. I.e.
>>> if you have
>>>
>>> cdef extern CppObject* foo()
>>>
>>> you can NOT do
>>>
>>> cdef CppObject obj = foo()
>>>
>>> It would only work when C++ returned an object *by value*:
>>>
>>> cdef extern CppObject foo()
>>> cdef CppObject obj = foo()
>>>
>>> This would then heap-allocate a CppObject, passing in the object
>>> that is
>>> returned to the copy constructor.
>>
>> Ah, ok, got it. So they'd basically be distinct types and you cannot
>> (implicitly) coerce a C++ object to a pointer. That should work then.
>
> Will dereferencing a CppObject pointer always create a Python object
> then? You could take the address of a CppObject and get a volitile
> pointer (just as with bytes -> char*), right?

&obj would be like bytes -> char*, same caveats

ptr[0] would (in my proposal anyway) return a Python object; BUT if that
is immedeately sent off to a C++ function by value it is just a
middle-person that can be left out safely, as an optimization.

> 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.

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.

Dag Sverre

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

Reply via email to