【问题标题】:Write a function that will return string after fetching message using FormatMessage编写一个函数,在使用 FormatMessage 获取消息后返回字符串
【发布时间】:2021-05-19 05:59:42
【问题描述】:

我想编写一个函数,它将 error_code 作为参数并获取错误消息并返回消息。但是对于 FormatMessage,分配的内存是通过使用 LocalFree(err_msg) 清除的。不知道怎么能不回来。

static char* return_message(int error_code) {
   LPTSTR err_msg;
   FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
            0, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR)&err_msg, 0, 0);
  return err_msg;

我想要一个类似于上面的方法。虽然在上述情况下,如果我们返回 err_msg 它超出了范围。任何人都可以为此提供适当的功能吗?

【问题讨论】:

  • 本地复制后返回std::unique_ptr<char[], CustomDeleter>,还是std::string

标签: c++ pointers scope formatmessage


【解决方案1】:

看到您正在使用 C++,您可以将生成的消息复制到 std::string 实例中,释放 C 字符串并返回副本。 std::string 的析构函数将在不再使用时处理释放。

#include <string>
#include <windows.h>

static std::string return_message(int error_code) {
   char* tmp_msg;
   FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
            0, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPSTR)&tmp_msg, 0, 0);

   std::string err_msg(tmp_msg);
   LocalFree(tmp_msg);
   return err_msg;
}

【讨论】:

  • FormatMessageA()的返回值为输出的字符数。我建议也将它传递给std::string 构造函数,例如:DWORD tmp_msg_len = FormatMessageA(...); std::string err_msg(tmp_msg, tmp_msg_len); 这样std::string 不必浪费时间计算字符来计算要复制多少。您还应该考虑使用try/catchstd::unique_ptr 来确保tmp_msg 被释放,即使std::string 构造函数抛出异常。
猜你喜欢
  • 2023-02-02
  • 2020-10-04
  • 1970-01-01
  • 2022-11-15
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
相关资源
最近更新 更多