gpt4 book ai didi

c++ - 托管 C++ dll 的加载程序锁定错误,静态链接到 native C++ 库

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:12:55 25 4
gpt4 key购买 nike

我有一个托管的 c++ dll,其中包含几个托管类,这些托管类依次调用库中的 native c++ 代码,我已静态链接到该 dll。但是,如果我尝试在 dll 上运行 RegAsm.exe,该工具会正确报告“我们没有注册任何类型”,但随后挂起。我很确定这是 loader lock问题,当 RegAsm 尝试加载它时我的 dll 挂起。我使用的是 Visual Studio 2008 速成版。

让我感到困惑的是,将 native 代码放入 dll 时一切正常,但从库中静态链接时却不行。我知道这篇文章类似于 this question但我的 dll 中没有没有 DllMain,因此我没有从 DllMain 运行 MSIL 代码的风险。此外,遵循对单个文件设置/clr 的建议也无济于事。

使用/NOENTRY 编译 dll 修复了锁定问题,但导致应用程序中断 Type initializer for <Module> threw exception异常(exception),显然只推荐与 .NET 2003 一起使用。

我怀疑静态成员的初始化可能是罪魁祸首,但我不明白为什么要在我的静态库中将其编译为 MSIL。

Just to clarify: although I have no need of running RegAsm.exe on the dll, I'm using it as a check for the loader lock problem. In reality I'm consuming the dll in a c# assembly that does implement few COM-visible classes - so I need to do COM registration on that one. At the end C# IDE crashes during registering for COM interop, reporting 'R6033 c++ runtime error: Attempt to use MSIL code from this assembly during native code initialization. This indicates a bug in your application. It is most likely the result of calling an MSIL-compiled (/clr) function from a native constructor or from DllMain.

解决了这个问题,但有些事情不清楚,我很好奇:

我注意到当事情停止工作时,两个静态变量被添加到静态链接库中的头文件,看起来像这样:

// The whole header is forced to compile as native 
#pragma managed(push, off)
....
static const std::locale commaSeparator(std::locale::classic(),
new DecimalSeparator<char>(','));;
....
#pragma managed(pop)

将初始化移动到 .cpp 文件(并将 static 更改为 extern )修复了加载程序锁。谁能指出为什么初始化程序会被编译为 MSIL?

修复之前,如果我只#included 来自托管 dll 的头文件,一切正常。但是,如果我包含 header 并且还链接到库,那么事情就不起作用了。由于 lib 也在内部使用 header ,我是否最终得到了静态变量的两个实例?无论如何,为什么要提示运行 MSIL 代码?

虽然现在一切正常,但欢迎任何见解。

最佳答案

Compiiler 用自己的代码包装用户定义的 DllMain,用于初始化运行时库和全局变量(这样用户定义的 DllMain 可以与已经创建的全局对象一起运行,并且可以使用标准库)。即使您没有 DllMain,仍然会有编译器生成的。使用/NOENTRY 可以指示链接器忽略它。

因此,在静态变量的构造函数中执行某些操作与在 DllMain 中执行操作实际上是一样的,这里似乎就是这种情况。

关于c++ - 托管 C++ dll 的加载程序锁定错误,静态链接到 native C++ 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7094397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com