C++ Windows DLL 使用 try-catch 块在内部失败

C++ Windows DLL using try-catch block internally fails

本文关键字:在内部 失败 try-catch 使用 Windows DLL C++      更新时间:2023-10-16

我正在尝试使用 gcc 版本 4.7.2 创建 Windows DLL,但是当我在内部使用异常时我遇到了问题。在 DLL 代码中,我抛出了一个在该方法中找到的异常test()该方法在同一方法中捕获。以下是在main.cpp中找到的代码:

#include <cstdlib>
#include <windows.h>
#include <iostream>
#include "dllexport.h"
using namespace std;
ADDAPI int test()
{
    try
    {
        throw 2;
    }catch(...)
    {
        std::cout << "Caught";
        return 1;
    }
    return 0;
}
//Link to correct DllMain if C++ is used
#ifdef __cplusplus
extern "C"
#endif
BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD  reason, LPVOID lpReserved)
{
    switch (reason)
    {
        case DLL_PROCESS_ATTACH:
        break;
        case DLL_THREAD_ATTACH:
        break;
        case DLL_THREAD_DETACH:
        break;
        case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

以及在 dllexport.h 中找到的相关标头

#ifndef DLLEXPORT_H
#define DLLEXPORT_H
/* Define calling convention in one place, for convenience. */
#define ADDCALL __stdcall
/* Usually format is ADDAPI int ADDCALL Add(int a, int b)...
   but moving ADDCALL near ADDAPI works in gcc */
/* You should define BUILDING_DLL *only* when building the DLL. */
#ifdef BUILDING_DLL
  #define ADDAPI __declspec(dllexport) ADDCALL
#else
  #define ADDAPI __declspec(dllimport) ADDCALL
#endif
#ifdef  __cplusplus
extern "C" {
#endif
    ADDAPI int test();
#ifdef  __cplusplus
}
#endif
#endif  /* DLLEXPORT_H */

这编译得很好,但是当我尝试从链接到它的进程调用测试方法时,返回以下错误:

此应用程序已请求运行时以异常方式终止它。

我使用以下方法编译 dll:

g++ -c main.cpp -O3 -DBUILDING_DLL
g++ -o mydll.dll main.o -shared -static-libgcc -static-libstdc++ -Wl,--add-stdcall-alias

此外,我使用 -lmydll 编译客户端应用程序。我知道从 DLL 中抛出异常并在进程中捕获它们是有风险的,但我没有这样做,因为异常将在 DLL 内部处理。

我做错了什么?

编辑:

删除 libstdc++ 到 DLL 的静态链接可以解决此问题。但是,如果 DLL 在内部解析所有依赖项,以便自包含,这将是理想的。我该怎么做才能达到上述目标?

我遇到了同样的问题,似乎我还必须使用以下行编译客户端应用程序

-static-libstdc++ -static-libgcc

为了它工作。