delegate for unmanaged callback

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

When using a delegate for callback from an unmanaged dll: do I have to fix (
(how do i?) that delegate somehow so that is will not be 'moved' on garbage
collection or voided totaly after the procedure is vacated so the unmanaged
pointer will loose it's relevance?
Thanks!
tb
 
Declare the delegate outside the function at the type level (assuming the
instance of the type is not eligible for GC, neither will the delegate). If
you are still in doubt, post your snippet.

Cheers
Daniel
 
Thanks Daniel, to make sure here's the code snippet:

public class WrapCDLL
{
public delegate void CallBack(IntPtr data);
static WrapCDLL()
....}

public class MyApp
{
public static WrapCDLL.CallBack myNotifyListenerDelegate;
public static void NotifyListener(IntPtr lpUnmanagedData)

{...}

public int Run() //the main loop entered after instantiating
MyApp

{myNotifyListenerDelegate = new
WrapCDLL.CallBack(NotifyListener);
......}
....}
 
Also - my question probably was unprecise: It's clear that GC won't destroy
the delegate as long as there is a valid reference (!=eligible for GC). But
what about moving it in memory and thereby changing it's address. (I thought
I had read somewhere that the GC might do this with managed types in order to
defragment memory usage?)
 
The CF actually keeps an internal pointer to it, so even if it needs to move
itt, it keeps track of that so you don't need to worry about pinning it.

-Chris
 
Thanks, wow that was quick!
Cheers
Theo

Chris Tacke said:
The CF actually keeps an internal pointer to it, so even if it needs to move
itt, it keeps track of that so you don't need to worry about pinning it.

-Chris
 
Back
Top