I am looking to have a portable debug class since i plan to work on the project on various platforms. This class provides methods to write messages through XDebug.WriteLine(“I like number %d”, 7); Which internally redirects the arguments to the system specific method.
This requires me to pass the ellipsis data as a parameter. And here is the problem. It works on integers, but loses floats on pass through.
XDebug::WriteLine("Print numbers %f, %f",1.234, 3.210f);
XDebug::odprintf(L"Print numbers %f, %f",1.234, 3.210f);
outputs
Print numbers 0.000000, 0.000000
Print numbers 1.234000, 3.210000
I am trying to figure out where the arguments get mangled. Would appreciate your help. The entire debug class is below.
#pragma once
#ifndef _XDEBUG_H_
#define _XDEBUG_H_
#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
#include <Windows.h>;
class XDebug
{
public:
static void __cdecl WriteLine(const char* txt, ...){
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
int stringSize = MultiByteToWideChar (CP_ACP, 0, txt, -1, NULL, 0);
wchar_t* buffer = new wchar_t[stringSize];
MultiByteToWideChar(CP_UTF8 , 0 , txt, -1, buffer, stringSize);
va_list args;
va_start(args, txt);
XDebug::odprintf(buffer,args);
delete buffer;
#endif
}
//private:
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
static void __cdecl odprintf(const wchar_t *format, ...){
wchar_t buf[4096], *p = buf;
va_list args;
int n;
va_start(args, format);
n = _vsnwprintf(p, sizeof buf - 3, format, args); // buf-3 is room for CR/LF/NUL
va_end(args);
p += (n < 0) ? sizeof buf - 3 : n;
while ( p > buf && isspace(p[-1]) )
*--p = '\0';
*p++ = '\r';
*p++ = '\n';
*p = '\0';
OutputDebugString(buf);
}
#endif
};
#endif
You cannot forward varargs between functions like that, for the same reason that you can’t pass
argsdirectly tosprintf(you have to use a specialvsprintf).I suggest writing an overload of
odprintfthat takes ava_listobject as a parameter. (And to avoid duplication, you could then implement the originalodprintfin terms of the new overload.)