Robert Bradshaw wrote:
> On May 6, 2009, at 5:33 AM, Dag Sverre Seljebotn wrote:
> 
>> Robert Bradshaw wrote:
>>> What about
>>>
>>> cdef CppObject a, b
>>> a = bar
>>> b = bar
>>> del a
>>> del b
>>>
>>> ?
>> Actually this *can* be supported by overloading operator new.
>>
>> I'll change the example to
>>
>> cdef CppObject a, b
>> a = CppObject(3)
>> b = CppObject(4)
>> del a
>> del b
>>
>> to avoid an unrelated and orthogonal issue with operator=. Then you  
>> can do:
>>
>> struct {} CythonOperators;
>>
>> void* operator new(size_t bytes, char* arg, CythonOperators foo) {
>> return arg; }
>> void operator delete(void* arg, CythonOperators foo) {/*noop*/}
>>
>> void f() {
>>    char a[sizeof(CppObject)];
>>    char b[sizeof(CppObject)];
>>
>>    new(a, CythonOperators) CppObject(3);
>>    new(b, CythonOperators) CppObject(4);
>>
>>    delete(CythonOperators) a;
>>    delete(CythonOperators) b;
>> }
>>
>> And /yes/, this is real C++ code... *sigh* :-) (though I'm not sure  
>> if I
>> got the details 100% right).
> 
> Actually, the new operator already supports passing in an address to  
> be used for memory, but I wasn't sure enough of how it worked to  
> bring it up. There's an issue of alignment as well.

Hmm. Interesting. Looked it up properly and tried it out, attaching for 
any future reference (though I suppose stack allocation is far down the 
line and after heap then).

Some memory is wasted for the alignment issue.

#include <iostream>
#include <new>

using namespace std;

class CppObject {
   int data;
public:
   CppObject(int d) : data(d) {
     cout << data << " construct" << endl;
   }
   ~CppObject() {
     cout << data << " destruct" << endl;
   }
};

int main () {
   void* __pyx_mem_a[(sizeof(CppObject) / sizeof(void*))+1];
   CppObject& __pyx_v_a = *(CppObject*)buf;
   new(buf) CppObject(4);

   // use __pyx_v_a as any stack allocated object

   co.~CppObject();
   cout << "done" << endl;
}

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

Reply via email to