Hi,
I have to handle unmanaged callback functions in my C# code. I am doing it
using delegates. I get the callback from the unmanaged code correctly with
valid data, but as soon as my managed (C#) callback handling method returns,
the app crashes. I suspected that this could be due to garbage collection of
the delegate and its associated unmanaged function pointer. I also used
GC.KeepAlive(..), but sadly I still get the crash. The other thing is I cant
debug into the app when it crashes. The debugger tells me that "Unhandled
Win32 Exception has occured in my exe". Even though I have enabled JIT
debugging it still tells me that JIT debugging is disabled. As such am unable
to debug into this issue further. Could anyone have some pointers for me to
look ahead? I have my source code below (housekeeping code has been removed
for brevity).
Thanks,
sushmair.
-Unmanaged code-
//the corresponding unmanaged function pointer.
//TNotificationType is a enum,THCMId is a typedef int
typedef void (*ptrToFn)(TNotificationType notifType, THCMId id, unsigned int
data1, unsigned int data2);
RegisterNotification(TNotificationType notifType,ptrToFn fnptr);
-Managed code-
//namespace
public delegate void Fptr(Int32 nottype,UInt32 id, UInt32 d1,UInt32 d2);
//the class
Class1
{
public static void DoSomething(Int32 notype,UInt32 id,UInt32 d1,UInt32 d2)
{
Console.WriteLine("not recvd...");
} // -->crashes here after returning
}
//In Main()
statuc void Main(string[] args)
{
Fptr cb = new Fptr(Class1.DoSomething);
GC.KeepAlive(cb);
LibWrap.RegisterNotification(1,cb); //LibWrap uses PInvoke to wrap around
the unmanaged code
Console.ReadLine(); //just to stop main from exiting
}
Willy Denoyette [MVP] - 21 May 2006 23:15 GMT
The default callback calling convention in Interop is stdcall, so you have
to change your typedef into:
typedef void (__stdcall *ptrToFn)...
Willy.
| Hi,
| I have to handle unmanaged callback functions in my C# code. I am doing it
[quoted text clipped - 43 lines]
| Console.ReadLine(); //just to stop main from exiting
| }
Sushrut - 22 May 2006 05:43 GMT
Thanks Willy! That works just great for me! :)
sushmair.
> The default callback calling convention in Interop is stdcall, so you have
> to change your typedef into:
[quoted text clipped - 57 lines]
> | Console.ReadLine(); //just to stop main from exiting
> | }