繁体   English   中英

C#如何导入ntdll.dll来使用NtDelayExecution和ZwSetTimerResolution?

[英]C# How to import ntdll.dll to use NtDelayExecution and ZwSetTimerResolution?

我是 C# 新手,我正在尝试使用 ntdll.dll 中的 NtDelayExecution 和 ZwSetTimerResolution 函数来创建自定义睡眠计时器。 (Thread.sleep 对我的应用程序来说不够精确)。 我尝试了许多不同的方法,但我不确定如何导入 ntdll.dll 以使用这两个函数。 两条静态 NTSTATUS 行是我试图转换为 C# 的部分 c++。 到目前为止我已经尝试过:

public unsafe static void GoSleep(float ms, float resolution = 0.5f)
        {

            if (resolution < 0.5) resolution = 0.5f;
            if (ms < resolution) ms = resolution;
         
            nuint res = (nuint)(resolution * 10000);
            nuint actualRes = 0;

            [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            internal static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

            [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
            public static extern IntPtr GetModuleHandle([MarshalAs(UnmanagedType.LPWStr)] in string lpModuleName);

            static NTSTATUS(__stdcall* NtDelayExecution)(bool Alertable, PLARGE_INTEGER DelayInterval) = (NTSTATUS(__stdcall*)(bool, PLARGE_INTEGER)) GetProcAddress(GetModuleHandle(X("ntdll.dll")), X("NtDelayExecution"));
            static NTSTATUS(__stdcall* ZwSetTimerResolution)(IN nuint RequestedResolution, IN bool Set, OUT pnuint ActualResolution) = (NTSTATUS(__stdcall*)(ULONG, BOOLEAN, PULONG)) GetProcAddress(GetModuleHandle(X("ntdll.dll")), X("ZwSetTimerResolution"));

            ZwSetTimerResolution(res, true, &actualRes);
         
            long LargeInteger = -1 * (long)(ms * 10000.0f);
         
            
            NtDelayExecution(false, &LargeInteger);
         
            ZwSetTimerResolution(res, false, &actualRes);
        }

导入它的最简单方法是使用 nuget。

  1. 右键单击nuget管理器

在此处输入图像描述

  1. 输入ntdll.dll,然后选择安装

在此处输入图像描述

暂无
暂无

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

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