avo
avo

Reputation: 10711

Does .NET interop cache the generated unmanaged thunks to managed method?

For example, I use unmanaged Win32 timer:

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void TimerProc(IntPtr hWnd, uint uMsg, IntPtr nIDEvent, uint dwTime);

[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
public static extern IntPtr SetTimer(IntPtr hWnd, IntPtr nIDEvent, 
    uint uElapse, TimerProc lpTimerFunc);

// ...

TimerProc timerProc = delegate { this.Beep(); };

// ...
var timerId = NativeMethods.SetTimer(IntPtr.Zero, IntPtr.Zero, 500, timerProc);

I wonder if the unmanaged pointer for lpTimerFunc which is passed to the actual SetTimer API remains the same for as longs as the managed timerProc remians the same, no matter how many times I call NativeMethods.SetTimer? Or does a new unmanaged thunk get generated for timerProc each time I call NativeMethods.SetTimer?

Upvotes: 1

Views: 227

Answers (1)

KC-NH
KC-NH

Reputation: 748

Each delegate will have its own thunk, so it depends on how you create your delegate. If you create a new delegate each time you call SetTimer, you'll have lots of them. If create it once for your class, you'll only have one.

Upvotes: 2

Related Questions