如何在 Windows 2016 服务器版本 1607 中访问 SetThreadDescription()

How to access SetThreadDescription() in Windows 2016 Server, Version 1607

如果我只是从 WinAPI 调用 SetThreadDescription(),它可以在 Windows 10,版本 2004 上运行。但是,在 Windows 2016 Server,1607 上它会产生以下消息框:

The procedure entry point SetThreadDescription could not be located in the dynamic link library

我的可执行程序的路径在消息中。

根据this article

SetThreadDescription is only available by Run Time Dynamic Linking on Windows Server 2016, 1607.

所以我尝试了如下动态链接:

typedef HRESULT (WINAPI *TSetThreadDescription)(HANDLE, PCWSTR);

namespace {
  TSetThreadDescription gpSetThreadDescription = nullptr;
}

void Initialize() {
  HMODULE hKernel32 = GetModuleHandleA("Kernel32.dll");
  if (hKernel32 == nullptr) {
    cerr << "FATAL: failed to get kernel32.dll module handle, error: " << GetLastError() << endl;
    quick_exit(5);
  }
  gpSetThreadDescription = reinterpret_cast<TSetThreadDescription>(
    GetProcAddress(hKernel32, "SetThreadDescription"));
  if (gpSetThreadDescription == nullptr) {
    cerr << "FATAL: failed to get SetThreadDescription() address, error: " << GetLastError() << endl;
    quick_exit(6);
  }
}

此代码也适用于 Windows 10。但是,我在 Windows Server 2016 上收到错误 127 ("The specified procedure could not be found")。

关于 运行 时间动态链接我做错了什么?

显然,尽管 MSDN 说 "DLL: Kernel32.dll",该函数实际上在 KernelBase.DLL 中,所以我在更改为:

后修复了问题
HMODULE hKernelBase = GetModuleHandleA("KernelBase.dll");