Pointers in extern DLL functions

Xavi ____nospam at nospam.com
Sat Dec 22 11:58:00 PST 2007


Jarrett Billingsley Wrote:

> "Xavi" <____nospam at nospam.com> wrote in message 
> news:fkhvrp$n0s$1 at digitalmars.com...
> > Hi all,
> >
> > I have a doubt, for example; is safe to send the pointer returned by 
> > toUTF16z() to a DLL extern function like in this code?
> > Can the GC delete it while the extern function is running? Do I need to 
> > keep it in a variable to avoid its deletion?
> >
> > capCreateCaptureWindowW(toUTF16z(title), 0, 0, 0, 0, 0, hwnd, 0);
> 
> The D GC is not asynchronous.  It will only collect on allocations. 
> Therefore, as long as this function doesn't allocate any memory *in your 
> app* (and it looks like it's a Windows API, so it doesn't look like that'll 
> happen) no collections can happen.  Even if one did, the reference to the 
> intermediately converted string would be sitting on the stack or in a 
> register and therefore it wouldn't be collected.
> 
> > And in this code using a cast? Is there any possible problem here?
> >
> > SendMessageW(hwnd, 0, 0, cast(uint)toUTF16z(file));
> 
> Not unless the GC becomes extremely precise and keeps track of exactly what 
> type every local variable is, which doesn't seem likely any time soon.  In 
> this case, even though it's a uint, it'll still be pointing into the GC heap 
> and won't be collected. 
> 
> 


Oops!, one more thing; I've read this in the manual of D: "Undefined behavior: Do not store pointers into non-pointer variables using casts and other tricks."

Then in this code 
SendMessageW(hwnd, 0, 0, cast(uint)toUTF16z(file));
the GC will not have any reference of the pointer returned by toUTF16z(), right?
I assume that if I run this code in a D multithreaded application another thread could call the GC collecting it while the SendMessageW() is running. Is this correct? 

Cheers, 
Xavi



More information about the Digitalmars-d-learn mailing list