views:

19

answers:

1

I get a protected memory exception, but how can I know which call caused it, and why the callback function has moved? All the calls to unmanaged code are done in the same class as the callback functions, so I suppose that the addresses should not change, or am I totally wrong here?

+2  A: 

For native code to call back into managed code you need a callback delegate (as long as we're not talking COM interop). And the most common reason for errors is that the callback delegate is garbage collected before the last callback occurs. It doesn't matter which class the callback target is defined in, but to keep the delegate alive is critical.

The ability to just specify the method name and let the C# compiler create a temporary delegate for you makes this error even more common. I.e. instead of

SetCallback(MyCallbackMethod);  // No good since you can't keep reference to delegate

do this

_callback = MyCallbackMethod;   // Create delegate explicitly and store reference at class level
SetCallback(_callback);

You can enable "managed debug assistants" to help you find this type of bug.

Mattias S