链接失败。如何使用'NtQuerySystemTime'窗口功能?

Linking failure. How to use 'NtQuerySystemTime' windows function?

本文关键字:窗口 功能 NtQuerySystemTime 失败 何使用 链接      更新时间:2023-10-16

我尝试使用以下简单代码来计算应用程序中的HDD写入速度:

#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文档说没有关联的导入库,我必须使用 LoadLibrary()GetProcAddress() 函数动态链接到Ntdll.dll。但是我不明白如何使用这些功能。有人可以提供如何使用这些功能的代码示例吗?

这就是您如何使用此功能。

HMODULE hNtDll = GetModuleHandleA("ntdll");
NTSTATUS (WINAPI *NtQuerySystemTime)(PLARGE_INTEGER) = 
    (NTSTATUS (WINAPI*)(PLARGE_INTEGER))GetProcAddress(hNtDll, "NtQuerySystemTime");
#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:%pn",fnNtQuerySystemTime);
        fnNtQuerySystemTime(SystemTime);
        printf("%llxn", SystemTime->QuadPart);
    }
    free(SystemTime);
}