转发省略号参数时丢失数据

Losing data when forwarding ellipsis args

本文关键字:数据 省略号 参数 转发      更新时间:2023-10-16

我希望有一个可移植的调试类,因为我计划在各种平台上处理该项目。这个类提供了通过XDebug.WriteLine("我喜欢数字%d",7)编写消息的方法;它在内部将参数重定向到系统特定的方法。

这需要我将省略号数据作为参数传递。这就是问题所在。它对整数有效,但在传递时会丢失浮点值。

XDebug::WriteLine("Print numbers %f, %f",1.234, 3.210f);
XDebug::odprintf(L"Print numbers %f, %f",1.234, 3.210f);

输出

Print numbers 0.000000, 0.000000
Print numbers 1.234000, 3.210000

我正试图弄清楚争论的症结所在。非常感谢你的帮助。下面是整个调试类。

#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 = '';
            *p++ = 'r';
            *p++ = 'n';
            *p   = '';
            OutputDebugString(buf);
    }
#endif
};
#endif

不能在这样的函数之间转发varargs,原因与不能将args直接传递给sprintf相同(必须使用特殊的vsprintf)。

我建议编写一个以va_list对象为参数的odprintf重载。(为了避免重复,您可以根据新的过载来实现原始的odprintf。)