Hi Cosmin
[quoted text, click to view] "CosminB [IXIA]" <cosminb@gmail.com> wrote in message
news:1157013225.064916.252860@i42g2000cwa.googlegroups.com...
> I've researched this matter for a couple of days now. I've seen samples
> of code, got them to work on small scale samples. The problem is that
> the final application is *critical* to our clients and our work. This
> is why I need to be 110% sure that what I'm asking about is correct.
>
> So, the problem is when the C++ DLL decides to callback the C# function
> I registered. When the callback was registered, it used code like: new
> MyCallback(SomeFunction), where MyCallback is a delegate type. Also,
> I've taken care of holding a reference to the created delegate during
> the period callbacks may 'strike'. But it is a known fact that this
> object could be moved in memory by the garbage collector at a later
> time. What happens then? Will the program crash? Does this even happen
> (the delegate being moved around in memory)? In my small scale tests,
> it looks like delegates are pinned in memory, but I doubt it. I need
> some insight from MSFT about how the delegates are implemented
> underneath. Maybe there are differences between regular delegates used
> by C# only, and the ones that are marshaled to C++ DLLs.
>
> I hope someone from MSFT can shed some light on this subject, I really
> need be sure about this.
>
I am not from Microsoft, but mabe I can help you, too.
Here are some facts that you should be aware of:
1) A P/Invoke function is via a Thunk.
2) If a function has non-isomorphic parameters, the thunk marshals all
parameters before the target method is called, and it probably marshals out
parameters and return values
3) delegates are non-trivial parameters that are marshaled specially
4) The delegate marshaling creates a special native proxy function that
calls the delegate
5) A pointer to this native proxy function is passed to the native target of
the P/Invoke call
6) This native proxy function does *not* reside on the GC heap - it resides
on a very special heap (that allocates memory pages with executin
permission)
7) This native proxy function is not relocated during GC.
8) This native proxy function lives on that heap at least as long as the
target delegate lives. (Therefore you are right to keep the delegate alive
"during
the period callbacks may 'strike'")
I do not guarantee that there is no bug in the P/Invoke layer with
delegates, but I can say that the technology behind this reasonable.
BTW. The ATL uses a very similar approach to generate proxy functions for
window procedures on the fly. If you are interested in that code, look at
atlstdthunk.h and atlthunk.cpp.
Hope this helps
Marcus Heege
[quoted text, click to view] > Best regards,
> Cosmin Banu.
>
> P.S. I need to know this for .NET v1.1 as well as v2.0. Primarily v1.1.
>