从单独的lib调用swprint失败

时间:2009-05-21 06:33:51

标签: c++ c unicode variadic-functions printf

我面临一个奇怪的问题。我根据构建定义使用sprintf或swprintf使用或不使用unicode。我已将这些函数包装在我自己的函数中,如下所示:

int mysprintf( MCHAR* str,size_t size, const MCHAR* format, ... )
{
#ifdef MYUNICODE
    return swprintf( str, size, format);
#else
    return snprintf( str, format);
#endif
}

这些函数位于String类中,该类是一个单独的项目,并编译为lib。我在另一个程序中使用它。现在,如果我使用mysprintf()

msprintf(str,10, _M("%d,%d"),height,width);

我在字符串缓冲区中获得了一些垃圾值。但是,如果我直接从程序中调用swprintf函数,它就会被罚款。我在构建中定义了UNICODE,并且函数swprintf被调用,但它填充了一些垃圾值。我不明白出了什么问题。

由于 阿米特

2 个答案:

答案 0 :(得分:1)

您需要将mysprintf函数中的...参数传递给它包含的prrintf函数。为此,您应该使用vprintf()系列函数 - 有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/0zf95wk0%28VS.71%29.aspx

答案 1 :(得分:1)

问题的确在于你拥有自己的函数,参数数量可变。您需要获取指向参数列表的指针并将其传递给callees。 va_start使您能够做到这一点,它需要参数列表中的最后一个指针指向您的函数。

   int mysprintf( MCHAR* str, size_t size, const MCHAR* format, ... )
    {
      va_list args;
      va_start(args, format);

      int result;

    #ifdef MYUNICODE
        result = vswprintf( str, size, format, args);
    #else
        result = ..
    #endif

      va_end(args);

      return result;
   }

干杯!