C++ 将 const char* 转换为 char* 用于长缓冲区
c++ converting const char* to char* for long buffer
我有一个旧功能,我无法更改 API
void TraceMsg(const char* fmt, ...)
{
if (!m_MessageFunctions[TraceLevel]) return;
char msgBuffer[MAX_LOG_MSG];
va_list argList;
va_start(argList, fmt);
vsnprintf(msgBuffer, MAX_LOG_MSG, fmt, argList);
va_end(argList);
m_MessageFunctions[TraceLevel](msgBuffer);
}
MAX_LOG_MSG = 2048
我进入了一个阶段,我想以动态方式为记录器的消息分配更多space
我已阅读这篇文章:https://code-examples.net/en/q/4904e5
并将我的代码更改为:
void TraceMsg(const char* fmt, ...)
{
if (!m_MessageFunctions[TraceLevel]) return;
va_list argList;
va_start(argList, fmt);
size_t size = vsnprintf(NULL, 0,fmt, argList);
char* msgBuffer = new char[size];
vsnprintf(msgBuffer, size, fmt, argList);
va_end(argList);
m_MessageFunctions[TraceLevel](msgBuffer);
delete[] msgBuffer;
}
我怎么会得到像
这样的奇怪角色
2022-05-03 12:13:20,939 INFO Make graph edge Bayer@LSC_1_2 ->Input@DeMux_LSC§§§§н
2022-05-03 12:13:20,939 INFO Make graph edge Bayer@RGB_IR_2_0 ->0@Mux_X2B_BP§§§§нннннњйн‚€нннннннннннннннннннннннннннннннннннн
你能帮忙吗?
vsnprintf
的return值为
The number of characters that would have been written if n had been
sufficiently large, not counting the terminating null character.
因此您需要为此加 1 以便为空终止符腾出空间。
我有一个旧功能,我无法更改 API
void TraceMsg(const char* fmt, ...)
{
if (!m_MessageFunctions[TraceLevel]) return;
char msgBuffer[MAX_LOG_MSG];
va_list argList;
va_start(argList, fmt);
vsnprintf(msgBuffer, MAX_LOG_MSG, fmt, argList);
va_end(argList);
m_MessageFunctions[TraceLevel](msgBuffer);
}
MAX_LOG_MSG = 2048
我进入了一个阶段,我想以动态方式为记录器的消息分配更多space
我已阅读这篇文章:https://code-examples.net/en/q/4904e5
并将我的代码更改为:
void TraceMsg(const char* fmt, ...)
{
if (!m_MessageFunctions[TraceLevel]) return;
va_list argList;
va_start(argList, fmt);
size_t size = vsnprintf(NULL, 0,fmt, argList);
char* msgBuffer = new char[size];
vsnprintf(msgBuffer, size, fmt, argList);
va_end(argList);
m_MessageFunctions[TraceLevel](msgBuffer);
delete[] msgBuffer;
}
我怎么会得到像
这样的奇怪角色2022-05-03 12:13:20,939 INFO Make graph edge Bayer@LSC_1_2 ->Input@DeMux_LSC§§§§н
2022-05-03 12:13:20,939 INFO Make graph edge Bayer@RGB_IR_2_0 ->0@Mux_X2B_BP§§§§нннннњйн‚€нннннннннннннннннннннннннннннннннннн
你能帮忙吗?
vsnprintf
的return值为
The number of characters that would have been written if n had been sufficiently large, not counting the terminating null character.
因此您需要为此加 1 以便为空终止符腾出空间。