Catching a DLL crash in C/C++

2019-03-31 09:30发布

问题:

I'm calling a function from a DLL, like this:

__declspec ( dllimport ) bool dll_function(...);

int main() {
  [...]
  if (dll_function(...)) {
    [...]
  }
}

In some cases, the data I pass to the DLL function will lead to a crash of the DLL. Is it possible to catch this so my application doesn't crash as well (without modifying the DLL which is not created by me)?

回答1:

You can catch AVs with the __try and __except keywords in the MSVC compiler. Not all that useful, you have no idea what kind of damage was done. The state of your program might well be corrupted. The heap might be blown for example, causing subsequent random failure. Hosting the DLL in its own process and using IPC to talk to it is the only decent approach.



回答2:

In some cases, the data I pass to the DLL function will lead to a crash of the DLL. Is it possible to catch this so my application doesn't crash as well?

Isn't it possible to prevent the dll from crashing if you only call the function with valid data? That should be the preferable solution in any case - but its hard to tell without knowing which dll you want to use. But in most cases, you should have an idea what "data" exactly results in an crash...



回答3:

Try looking at:

http://msdn.microsoft.com/en-us/library/ms680634%28v=vs.85%29.aspx

and

Enforce Filter code by Oleg Starodumov (www.debuginfo.com)

http://www.debuginfo.com/articles/debugfilters.html

However, that is a top level filter and not a try/catch. You can perhaps restart your process.

You might need to use __try for exceptions. Again, probably better to fix the problem or just crash than to try to catch it. I agree with the others that rather than suppressing or hiding the crash you should fix it. I don't know how well you can recover from the crash - is it going to be useful to continue execution after something like that?



回答4:

I'm not sure if this is the problem, try specifying the correct calling convention. (__stdcall, __cdecl, etc).

If that's not the problem, we need to see what you are passing to the function and possibly the function code if you have it.



标签: c++ c dll crash