链接失败。如何使用'NtQuerySystemTime'窗口函数?

时间:2013-10-28 21:44:34

标签: c++ winapi dll time

我尝试使用这个简单的代码来计算我的应用程序中的硬盘写入速度:

#include <winternl.h>

...
float speed;
double divident;
PLARGE_INTEGER systime0, systime1;
LONGLONG elapsed_time;
...

write_flag = true ;

NtQuerySystemTime(systime0) ;

f_out->write(out_buffer0, chunk_len0);
f_out->write(out_buffer1, chunk_len1);

NtQuerySystemTime(systime1);

elapsed_time = systime1->QuadPart - systime0->QuadPart;

write_flag = false ;

divident = static_cast<double>(chunk_len0 + chunk_len1) / 1.048576 ;  // 1.024 * 1.024 = 1.048576; divident yield value 1000000 times greater then value in MB
divident *= 10 ;  // I want 'speed' to be in MB/s
speed = divident / static_cast<double>(elapsed_time) ;
...

但无法链接。

在MSDN上,NtQuerySystemTime documentation表示没有关联的导入库,我必须使用LoadLibrary()GetProcAddress()函数动态链接到Ntdll.dll。但我不明白如何使用这些功能。有人可以提供一个如何使用这些功能的代码示例吗?

2 个答案:

答案 0 :(得分:1)

这就是你可以使用这个功能的方法。

HMODULE hNtDll = GetModuleHandleA("ntdll");
NTSTATUS (WINAPI *NtQuerySystemTime)(PLARGE_INTEGER) = 
    (NTSTATUS (WINAPI*)(PLARGE_INTEGER))GetProcAddress(hNtDll, "NtQuerySystemTime");

答案 1 :(得分:1)

#include <stdio.h>
#include <windows.h>

typedef  NTSYSAPI (CALLBACK *LPNTQUERYSYSTEMTIME)(PLARGE_INTEGER);

void main(void)
{
    PLARGE_INTEGER  SystemTime;
    SystemTime = (PLARGE_INTEGER) malloc(sizeof(LARGE_INTEGER));

    HMODULE hNtDll = GetModuleHandleA("ntdll");

    LPNTQUERYSYSTEMTIME fnNtQuerySystemTime = (LPNTQUERYSYSTEMTIME)GetProcAddress(hNtDll, "NtQuerySystemTime");

    if(fnNtQuerySystemTime){

        printf("found NtQuerySystemTime function at ntdll.dll address:%p\n",fnNtQuerySystemTime);
        fnNtQuerySystemTime(SystemTime);
        printf("%llx\n", SystemTime->QuadPart);

    }

    free(SystemTime);
}