How can I detect which callback from an unmanaged dll causes a protected memory exception?
I get a protected memory e开发者_开发百科xception, 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?
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.
精彩评论