C++ Windows DLL 使用 try-catch 块在内部失败
C++ Windows DLL using try-catch block internally fails
我正在尝试使用 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
为了它工作。
相关文章:
- 如何在公共头文件中向库的用户公开枚举,同时在内部使用它?
- std::strlen 在内部是如何工作的?
- STRCMP内部IF在内部不起作用
- 为什么我的Qt程序在断言失败后继续运行?
- "std::string"是否将其字符作为签名字符在内部存储?
- WriteProcessMemory 在函数内部失败
- 虚拟基类在内部如何工作?编译器如何解析对基方法的调用?
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- C++:在"try"外部创建的类型会导致错误,但在内部不会
- 访问说明符(私有/公共/受保护)如何在内部工作(限制成员访问)?
- 特征运算符如何在内部解释为 MKL 函数?
- 指向C++中成员的指针如何在内部工作?
- 删除和删除[]在内部如何工作?
- 自动参数如何在内部工作
- C++放置位置删除如何在内部(C++运行时)工作?如何克服其局限性?
- 在Win64失败上构建OpenSSL
- 在内部使用ComboBox拖动ListWidget项目
- 为什么实体可以在内部范围内重用?C++
- 如果不允许我分配 rvalues 来引用为什么以下代码片段有效,这在内部如何工作?
- C++ Windows DLL 使用 try-catch 块在内部失败