__declspec(dllimport) how to load library

Deadly 提交于 2019-11-29 03:49:29
CharlesB

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

  1. include the .lib in the Linker options
  2. provide the DLL at runtime so that it's found by the exe

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).

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(dllimpport).

The linker is provided with the .lib file, and generates appropriate instructions in the 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).

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

If you are using a DLL, you can to use the LoadLibrary and GetProcAddress combination.

//Load the DLL
HMODULE lib = LoadLibrary("testing.dll");

//Create the function
typedef void (*FNPTR)();
FNPTR myfunc = (FNPTR)GetProcAddress(lib, "myfunc");

//EDIT: For additional safety, check to see if it loaded
if (!myfunc) {
    //ERROR.  Handle it.
}

//Call it!
myfunc();

Your operating system will be able to find it based on the linking process. If your library is linked properly to your program, it will recognize that there is an external function being used, and look for it in the dll paths. If it can't find it, your linker will throw an error.

I recommend doing some reading into the linking process; it can be confusing at times but understanding it may help you grasp some key concepts in C/C++.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!