关于C#:WinApi FormatMessage导致段错误

WinApi FormatMessage causes segfault

我使用CodeBlocks和Mingw:g版本为4.7.1

来自MSDN的示例(请参见最后一个示例,位于"需求"部分之前):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Formats a message string using the specified message and variable
// list of arguments.
LPWSTR GetFormattedMessage(LPWSTR pMessage, ...)
{
   LPWSTR pBuffer = NULL;

   va_list args = NULL;
   va_start(args, pMessage);

   FormatMessage(FORMAT_MESSAGE_FROM_STRING |
              FORMAT_MESSAGE_ALLOCATE_BUFFER,
              pMessage,
              0,
              0,
              (LPWSTR)&pBuffer,
              0,
              &args);

   va_end(args);

   return pBuffer;
}

在调用FormatMessage时出现段错误。
您是否知道为什么会发生这种情况以及我该如何解决?

这是我的称呼:

1
2
int x = 3, y = 5;
GetFormattedMessage(_T("%1 : %2"), x, y);

我使用FormatMessage是因为我无法在mingw上使用_stprintf函数,_stprintf是swprintf的定义,而swprintf本身并未定义为某些bug的修复%)


FormatMessage要求您在消息字符串中传递类型信息。如果不这样做,则假定您的参数是C样式字符串。 MSDN说:

The default is to treat each value as a pointer to a null-terminated string.

当您传递整数而不是字符串时,您的调用应类似于:

1
GetFormattedMessage(_T("%1!d! : %2!d!"), x, y);