0

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?

Victor
  • 13,914
  • 19
  • 78
  • 147
  • keep in mind that `string_length` may represent the size of a `std::wstring`, and `std::wstring` has `wchar_t`, which one can be, for instantece 2 bytes. So there is a chance that you must do a `byte conversion`... something like m_raw_content.length()*sizeof(wchar_t), of course depending on your `output.Format` implementation. – wesley.mesquita Jan 27 '14 at 13:56
  • the `output` variable is just for diagnosing. I have written that because that method is not working. – Victor Jan 27 '14 at 14:01
  • Are the string resources embedded in the DLL? – benjymous Jan 27 '14 at 14:06
  • yes, they are embedded in the DLL – Victor Jan 27 '14 at 14:09
  • So, Did you check the value of `string_length`? What is the value? – hyun Jan 27 '14 at 14:13

2 Answers2

2

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.)

Community
  • 1
  • 1
benjymous
  • 2,102
  • 1
  • 14
  • 21
0

Take a look at this question, which will show you how to get the HINSTANCE of your DLL if it's an MFC DLL.

Community
  • 1
  • 1
Sean
  • 60,939
  • 11
  • 97
  • 136