简体   繁体   English

动态库执行时链接

[英]Dynamic library Linking at execution

why did it fail to load the library at link at compilation time? 为什么在编译时无法在链接加载库? i don't care about freeing the library yet it just won't work. 我不关心释放图书馆,但它不会工作。

#include <windows.h>

    int main()
    {
        LoadLibrary("winmm.lib");
        timeGetTime();
    }

.lib is not a dynamically linked library (DLL), and cannot be loaded at runtime. .lib不是动态链接库(DLL),无法在运行时加载。 You need to load the .dll , or link the .lib at link time (at which point you don't use LoadLibrary). 您需要加载.dll ,或在链接时链接.lib (此时您不使用LoadLibrary)。

Try this code. 试试这个代码。 It should solve your problem. 它应该解决你的问题。

#include <windows.h>

#pragma comment(lib, "winmm.lib")

int main()
{
    DWORD time = timeGetTime();
}

From your comment above, it's clear that the problem is that timeGetTime() requrires the winmm module at compile time, which means you have to link with winmm.lib. 从上面的评论中可以看出,问题是timeGetTime()在编译时需要winmm模块,这意味着你必须与winmm.lib链接。 You cannot call the function directly by its name if you want to use run-time linking; 如果要使用运行时链接,则不能通过其名称直接调用该函数; you have to get its function pointer out of the DLL. 你必须从DLL中获取它的函数指针。

If you truly want to load the DLL at run time, you must use GetProcAddress . 如果您确实要在运行时加载DLL,则必须使用GetProcAddress A full set of example code for using LoadLibrary properly is found on this MSDN page . 在此MSDN页面上可以找到正确使用LoadLibrary的完整示例代码。

You are trying to load a .lib file (linker library information) using the LoadLibrary function, which is designed to load dynamic-link libraries - that is plain wrong. 您正在尝试使用LoadLibrary函数加载.lib文件(链接器库信息),该函数用于加载动态链接库 - 这是完全错误的。 .lib files are linked in the executable at link time, whereas the .dll files are loaded at runtime, either via explicit loading using LoadLibrary or by feeding the linker a .lib file that references a .dll file. .lib文件在链接时链接在可执行文件中,而.dll文件在运行时加载,可以通过使用LoadLibrary显式加载,也可以通过向链接器提供引用.dll文件的.lib文件。

  • If you want to load a static library you need to tell the linker to include it - consult your compiler's documentation about this. 如果要加载静态库,则需要告诉链接器包含它 - 请参阅编译器有关此文档的文档。
  • To load a dynamic library using a .lib file, you need to do the same as for a static library and put the dynamic library in the global PATH or in the same directory as the executable. 要使用.lib文件加载动态库,您需要执行与静态库相同的操作,并将动态库放在全局PATH或与可执行文件相同的目录中。
  • To load a dynamic library at runtime you need to call LoadLibrary to get a handle to it and pass that to GetProcAddress to get pointers to the functions you are interested in. Wikipedia has a small example on how to do this . 要在运行时加载动态库,您需要调用LoadLibrary来获取它的句柄并将其传递给GetProcAddress以获取指向您感兴趣的函数的指针.Wikipedia 有一个关于如何执行此操作的小示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM