简体   繁体   中英

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?

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

看看这个问题 ,它将告诉你如何获得你的DLL的HINSTANCE ,如果它是一个MFC DLL。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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