c++dllmfcresourcesstring-table

LoadString() method doesn't work in C++


I am trying to load a string from my Strin Table in the DLL file I am working on. Here is the function that is supposed to load the string into a std::wstring (since my project uses Unicode charset).

void ErrorHandler::load_error_string()
{
  m_hInst = AfxGetInstanceHandle();
  wchar_t buffer[1024] = { '\0' };
  std::size_t string_length = LoadStringW(this->m_hInst, this->m_error_id, buffer, 1024);

  this->m_raw_content = std::wstring(buffer, string_length);

  CStringW output;
  output.Format(L"%d", m_raw_content.length());

  AfxMessageBox(output);
}

I have created the last three lines for diagnosing the method. The output of AfxMessageBox() is 0.

Where am I wrong?


Solution

  • AfxGetInstanceHandle() gives you the HINSTANCE of the running executable. This means that your LoadStringW call will be looking in the exe's resource table for your string, which will fail, as the strings are in your DLL.

    Instead, you'll need to grab the HINSTANCE of the DLL itself - this is provided as the first parameter to DllMain() in your DLL.

    See this answer for an example: https://stackoverflow.com/a/2396380/1073843

    EDIT: If you're using an MFC DLL, then it's possible you just need to add a call to AFX_MANAGE_STATE(AfxGetStaticModuleState()); at the top of any entry points into your DLL (before AfxGetInstanceHandle() is called.)