__declspec(dllimport) 如何加载库

2021-12-25 00:00:00 dll c++ dllexport

http://msdn.microsoft.com/en-us/library/9h658af8.aspx

MSDN 说我可以使用 __declspec(dllexport) 从库中导出函数,但是如何在我的可执行文件中加载这个库?

MSDN says I can export function from the library with __declspec(dllexport) but how can I load this library in my executable?

我在 DLL 中有一个导出函数:

I've got an exported function in DLL:

 __declspec(dllexport) void myfunc(){}

现在我想在我的可执行文件中使用它:

And now I would like to use it in my executable:

 __declspec(dllimport) void myfunc(void);

但是我的程序如何知道在哪里可以找到这个函数?

But how my program will know where to find this function?

推荐答案

这是编译器/链接器的工作,只要你自动完成

This is the compiler/linker job, it's done automatically as long as you

  1. 在链接器选项中包含 .lib
  2. 在运行时提供 DLL,以便 exe 找到它

.lib 文件是在您编译 DLL 时生成的,或者如果它不是您的代码,则随它一起提供.在这种情况下,代码使用 __declspec(dllexport) 编译.

The .lib file is generated when you compile the DLL, or is shipped with it if it's not your code. In this case the code is compiled with __declspec(dllexport).

在编译你的exe时,编译器看到包含的函数是在DLL中找到的.在这种情况下,代码使用 __declspec(dllimport) 编译.

When compiling your exe, the compiler sees that the included function is to be found in DLL. In this case the code is compiled with __declspec(dllimport).

链接器随 .lib 文件一起提供,并在 exe 中生成适当的指令.

The linker is provided with the .lib file, and generates appropriate instructions in the exe.

这些指令将使 Exe 找到 DLL 并在运行时加载导出的函数.DLL 只需要在 Exe 旁边(但是,还有其他可能的位置).

These instructions will make the Exe find the DLL and load the exported function at runtime. The DLL just has to be next to the Exe (there are other possible places, however).

__declspec(dllimport)__declspec(dllexport) 之间的切换是由一个宏完成的,在创建 DLL 项目时由 Visual C++ 提供.

Switching between __declspec(dllimport) and __declspec(dllexport) is done by a macro, provided by Visual C++ when creating a DLL project.

相关文章