Running a delegate inside a C function

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 7 14:40:44 PDT 2014


On Saturday, 7 June 2014 at 21:18:39 UTC, Denis Martinez wrote:
> Thanks for the answer Chris, you are correct.
> I was expecting the closure to work similarly to Clang's 
> blocks, which apparently it does not. I guess that delegates 
> pass by copy, like structs do.
>
> So far I have tried a variety of solutions.
>
> 1. As it is, passing the delegate as "ref" does not work, 
> because the compiler does not accept to do the implicit 
> conversion. It is the same logic as C++, here in C++11 I would 
> have passed by rvalue reference, a thing that does not appear 
> to exist in D.
>
> 2. Is it possible to make a delegate to be allocated on the 
> heap ?
> I think of a syntax such as:
>   client.process_callback = new delegate int(jack_nframes_t 
> nframes) {
>
> 3. I have coded a workaround for the time being.
> The function here copies the delegate into a heap-allocated 
> structure, and takes the interior pointer.
>
>   T *copyDelegate(T)(T dg) {
>     struct Tmp { T dg; }
>     auto x = new Tmp;
>     x.dg = dg;
>     return &x.dg;
>   }
>
> I find this code to be rather inelegant, is there a better 
> solution?

&[dg][0] maybe

But you're storing dg in your (heap because class) object anyway,
as process_callback_. Just do that first and use
&process_callback_ instead of &dg. That also guarantees that
there's a pointer to it in D-land so that the GC doesn't collect
it.


More information about the Digitalmars-d-learn mailing list