Search code examples
c++multithreadingwinapidllwindows-server-2016

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


If I just call SetThreadDescription() from WinAPI, it works on Windows 10, Version 2004. However, on Windows 2016 Server, 1607 it produces the following message box:

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

and the path to my executable program follows in the message.

According to this article:

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

So I tried dynamic linking as follows:

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);
  }
}

This code also works on Windows 10. However, I'm getting error 127 ("The specified procedure could not be found") on Windows Server 2016.

What am I doing wrong about the run-time dynamic linking?


Solution

  • Apparently, despite MSDN says "DLL: Kernel32.dll", the function is actually in KernelBase.DLL, so I've fixed the problem after changing to:

    HMODULE hKernelBase = GetModuleHandleA("KernelBase.dll");