在 C/C++ 中捕获 DLL 崩溃

2022-01-12 00:00:00 dll c crash c++

我正在从 DLL 中调用一个函数,如下所示:

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

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

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

在某些情况下,我传递给 DLL 函数的数据会导致 DLL 崩溃.是否有可能捕捉到这一点,这样我的应用程序也不会崩溃(不修改不是我创建的 DLL)?

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)?

推荐答案

您可以在 MSVC 编译器中使用 __try 和 __except 关键字捕获 AV.不是那么有用,你不知道造成了什么样的损害.您的程序的状态很可能已损坏.例如,堆可能被炸毁,导致随后的随机故障.将 DLL 托管在自己的进程中并使用 IPC 与其通信是唯一合适的方法.

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.

相关文章