如何在 C++ 中使用 LoadLibrary(..) 调用 kernel32.dll 函数 GetTickCount() [英] How to call a kernel32.dll function GetTickCount() using LoadLibrary(..) in C++

查看:21
本文介绍了如何在 C++ 中使用 LoadLibrary(..) 调用 kernel32.dll 函数 GetTickCount()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个函数来在 Windows 机器上以毫秒为单位获取时间.本质上,我想调用这个 WinAPI 函数 GetTickCount(),但我被困在使用 LoadLibrary(...) n 调用 GetTickCount() 函数"部分..

I am searching for a function to get time in milliseconds on a windows machine. Essentially, I want to call this WinAPI function GetTickCount(), but I'm stuck on "use LoadLibrary(...) n call GetTickCount() function" part..

我搜索了每个论坛并用谷歌搜索了它,但到处都有人使用无法编译的不完整代码..谁能编写一个简短的示例程序来加载 kernel32.dll 并调用 GetTickCount() 以显示以毫秒为单位的时间?

I searched every forum n googled it but everywhere people have used incomplete codes that don't compile..Can anyone write a short sample program to load kernel32.dll and call GetTickCount() to display the time in milliseconds?

请编写可编译的代码!

推荐答案

您无法加载 kernel32.dll,它已经加载到每个进程中.并且 GetTickCount 存在于每个版本的 Windows 上,因此您不需要 GetProcAddress 来查看它是否存在.您只需要:

You can't load kernel32.dll, it's already loaded into every process. And GetTickCount exists on every version of Windows, so you don't need GetProcAddress to see if it exists. All you need is:

#include <windows.h>
#include <iostream>

int main(void)
{
    std::cout << GetTickCount() << std::endl;
}

动态加载示例(因为 winmm.dll 未预加载):

A dynamic load example (since winmm.dll is not preloaded):

#include <windows.h>
#include <iostream>

int main(void)
{
    HMODULE winmmDLL = LoadLibraryA("winmm.dll");

    if (!winmmDLL) {
        std::cerr << "LoadLibrary failed." << std::endl;
        return 1;
    }

    typedef DWORD (WINAPI *timeGetTime_fn)(void);
    timeGetTime_fn pfnTimeGetTime = (timeGetTime_fn)GetProcAddress(winmmDLL, "timeGetTime");

    if (!pfnTimeGetTime) {
        std::cerr << "GetProcAddress failed." << std::endl;
        return 2;
    }

    std::cout << (*pfnTimeGetTime)() << std::endl;
    return 0;
}

我已使用 Visual Studio 2010 命令提示符成功编译并运行此示例,不需要特殊的编译器或链接器选项.

I've successfully compiled and run this example using Visual Studio 2010 command prompt, no special compiler or linker options are needed.

这篇关于如何在 C++ 中使用 LoadLibrary(..) 调用 kernel32.dll 函数 GetTickCount()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆