加载托管 C++ 来自普通 C++ 的 DLL 通过 LoadLibrary 进行编程
我正在尝试在托管 C++ 和普通 C++ 之间实现简单的混合工作。 我正在使用 Visual Studio 2005,但一直遇到问题。 这是我的设置。
首先,我有一个从代码构建的简单 DLL
#using "mscorlib.dll"
#include "windows.h"
__declspec(dllexport)
void sayHello()
{
OutputDebugStringA( "Hello from managed code!" );
}
我使用在命令行上将其编译为 DLL
cl /CLR /LD dllcode.cpp
接下来,我有一个简单的程序,仅包含
#include <windows.h>
int main()
{
HINSTANCE lib = LoadLibrary( "dllcode.dll" );
if ( !lib ) {
return 1;
}
return 0;
}
我使用它构建一个应用程序
cl loader.cpp
所以我最终得到 dllcode .dll
和 loader.exe
在同一目录中。 当尝试运行loader.exe
时,我总是得到返回代码“1”。 查找 GetLastError()
产生的错误代码显示加载 dllcode.dll
由于 找不到指定的模块而失败。
有人知道吗?知道为什么会这样吗? 它与需要嵌入到 dllcode.dll 中的清单有关吗? 我在 dllcode.dll 上运行了 dependent 程序,但据我所知,它没有产生任何问题。
I'm trying to get a simple mixture between Managed C++ and plain C++ working. I'm using Visual Studio 2005 but keep hitting a problem. Here's my setup.
First, I have a simple DLL built from the code
#using "mscorlib.dll"
#include "windows.h"
__declspec(dllexport)
void sayHello()
{
OutputDebugStringA( "Hello from managed code!" );
}
I compile this on the commandline to a DLL using
cl /CLR /LD dllcode.cpp
Next, I have a simple program consisting of nothing more than
#include <windows.h>
int main()
{
HINSTANCE lib = LoadLibrary( "dllcode.dll" );
if ( !lib ) {
return 1;
}
return 0;
}
I build an application out of this using
cl loader.cpp
So I end up with dllcode.dll
and loader.exe
in the same directory. When trying to run loader.exe
, I always get return code '1'. Looking up the error code yielded by GetLastError()
shows that loading dllcode.dll
failed due to The specified module could not be found.
Does anybody know why this could be? Does it have something to do with manifests which need to be embedded into dllcode.dll
or so? I ran the depends program on dllcode.dll but it didn't yield any problems as far as I could tell.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我刚刚发现为什么从我的普通 C++ 程序加载托管 C++ DLL 不起作用。 再次感谢 jdigital 给我指出了一个有用的工具:
错误的根源是找不到 MSVC8 运行时库。 我认为构建via时生成的清单
已经嵌入到DLL中了。 显然,它不是 - 所以加载程序无法找到适当的 MSVCR80.dll 副本。
我通过在 DLL 构建例程中添加第二步解决了这个问题:
希望这会有所帮助。 我怀疑这是一个初学者问题......
I just found out why loading the Managed C++ DLL from my vanilla C++ program didn't work. Thanks once again to jdigital for pointing me to a useful tool:
The source of the error was that the MSVC8 runtime library was not found. I thought that the manifest which is generated when building via
is already embedded into the DLL. Apparently, it's not - so the loader failed to locate the appropriate MSVCR80.dll copy.
I fixed this problem by adding a second step to the DLL building routine:
Hope this helps. Quite a beginner problem, I suspect...
您可以尝试使用 filemon 来查看 LoadLibrary 尝试加载的内容。
You might try using filemon to see what LoadLibrary is trying to load.