views:

76

answers:

2

Hi all

I am facing a strange problem. I am using sprintf or swprintf according to the build defines with or without unicode. I have wrapped these functions in my own function like this:

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

These function are in a String class which is a separate project and is compiled as a lib. I use it in another program. Now if I use the mysprintf()

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

I get some garbage values in the string buffer. But if I directly call the swprintf function from the program it works fines. I have defined UNICODE in the build and the function swprintf does get called, but it fills some garbage values. I dont understand what is going wrong.

Thanks Amit

+1  A: 

You need to pass the the ... parameters from the mysprintf function to the prrintf functions it contains. To do this, you should be using the vprintf() family of functions - see http://msdn.microsoft.com/en-us/library/0zf95wk0%28VS.71%29.aspx for details.

anon
+1  A: 

The problem indeed lies in that you have your own function with variable number of parameters. You need to get a pointer to the list of arguments and pass that on to the callees. va_start enables you to do just that and it needs the last pointer in the argument list to your function.

   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;
   }

Cheers !

Magnus Skog
Thanks Magnus, this cleared the concept.
amit
Anytime mate :)
Magnus Skog
swprintf() doesn't take a va_list, but vswprintf() does.
bk1e
Thanks mate. I just copied and pasted the code above, but should have read it more carefully. Edited now :)
Magnus Skog