Reference to D class instance with a C library

Leandro Motta Barros lmb at stackedboxes.org
Sat Jul 13 11:53:49 PDT 2013


Hey, thanks! This makes sense :-)

Am I now wondering... how safe, portable and future proof would this
be? If some future version of D implements a garbage collector capable
of moving objects around the heap, I could get in trouble, right?

LMB


On Sat, Jul 13, 2013 at 3:35 PM, Adam D. Ruppe
<destructionator at gmail.com> wrote:
> On Saturday, 13 July 2013 at 18:30:24 UTC, Leandro Motta Barros wrote:
>>
>> So, is there some way to store a reference to a D class instance in that
>> 'user_data' field?
>
>
> Should be ok to cast the reference itself to that type - don't take the
> address of it, since that would be the address of a local, but just cast it:
>
> MyObject foo = new MyObject();
>
> c_struct.user_data = cast(intptr_t) foo;
>
> And when you get it back:
>
> foo = cast(MyObject) c_struct.user_data;
>
>
> In D, MyObject is already basically a MyObject*, so if you did &foo, the
> type would be more like MyObject** which is probably why you didn't have
> luck doing it before.


More information about the Digitalmars-d-learn mailing list