none
p/invoke, delegates, garbage collector and relocation RRS feed

Answers

  • When a delegate is passed to unmanaged code, the CLR creates a thunk on the unmanaged heap that holds onto the internal GC delegate location and hands a function pointer of its own to the native code. This won't move around in memory, and it will forward on to the real delegate when it's invoked.
    • Marked as answer by MarkusSchaber Tuesday, August 17, 2010 10:54 AM
    Monday, August 16, 2010 4:12 PM
  • You're on the right track. The thunk contains a weak reference to the delegate, and when the delegate is collected then the associated thunk will also be collected. If that happens, the unmanaged function pointer becomes invalid and invoking the callback from unmanaged code will give you an access violation. It's up to the code that created the callback to manage its expected lifetime if it's needed for more than the duration of the initial call.
    • Marked as answer by MarkusSchaber Wednesday, August 18, 2010 7:07 AM
    Tuesday, August 17, 2010 4:17 PM

All replies

  • When a delegate is passed to unmanaged code, the CLR creates a thunk on the unmanaged heap that holds onto the internal GC delegate location and hands a function pointer of its own to the native code. This won't move around in memory, and it will forward on to the real delegate when it's invoked.
    • Marked as answer by MarkusSchaber Tuesday, August 17, 2010 10:54 AM
    Monday, August 16, 2010 4:12 PM
  • Hi, Chris,

    Okay, I see.

    But when the GC knows to update the pointer inside the thunk when he relocates the delegate, how comes that the GC does not consider the thunk when calculating the "aliveness" of the delegate? Is that thunk keeping a kind of weak reference to the delegate? And how are the thunks collected when the delegate is not used any more?

    Thanks,
    Markus

    Tuesday, August 17, 2010 10:53 AM
  • You're on the right track. The thunk contains a weak reference to the delegate, and when the delegate is collected then the associated thunk will also be collected. If that happens, the unmanaged function pointer becomes invalid and invoking the callback from unmanaged code will give you an access violation. It's up to the code that created the callback to manage its expected lifetime if it's needed for more than the duration of the initial call.
    • Marked as answer by MarkusSchaber Wednesday, August 18, 2010 7:07 AM
    Tuesday, August 17, 2010 4:17 PM
  • Hi, Chris,

    Now I understand. So the finalizer of the delegate (or some similar mechanism) deallocates the unmanaged thunk.

    Thanks for the enlightenment.

    Wednesday, August 18, 2010 9:34 AM
  • Hi. Is this still valid as of 2019. Also does it make any difference if I am using .net Core 2/3?


    Friday, March 22, 2019 6:39 AM