How do I convert from _TCHAR * to char * when using C++ variable-length args?

Nick Bolton picture Nick Bolton · Oct 23, 2009 · Viewed 21.7k times · Source

We need to pass a format _TCHAR * string, and a number of char * strings into a function with variable-length args:

inline void FooBar(const _TCHAR *szFmt, const char *cArgs, ...) {
  //...
}

So it can be called like so:

char *foo = "foo";
char *bar = "bar";
LogToFileA(_T("Test %s %s"), foo, bar);

Obviously a simple fix would be to use _TCHAR instead of char, but we don't have that luxury unfortunately.

We need to use this with va_start, etc so we can format a string:

va_list args;
_TCHAR szBuf[BUFFER_MED_SIZE];

va_start(args, cArgs);
_vstprintf_s(szBuf, BUFFER_MED_SIZE, szFmt, args);
va_end(args);

Unfortunately we cannot use this because it give us this error:

Unhandled exception at 0x6a0d7f4f (msvcr90d.dll) in foobar.exe:
0xC0000005: Access violation reading location 0x2d86fead.

I'm thinking we need to convert our char * to _TCHAR * - but how?

Answer

Remy Lebeau picture Remy Lebeau · Oct 24, 2009

Use %hs or %hS instead of %s. That will force the parameters to be interpretted as char* in both Ansi and Unicode versions of printf()-style functions, ie:

inline void LogToFile(const _TCHAR *szFmt, ...)
{  
  va_list args;
  TCHAR szBuf[BUFFER_MED_SIZE];

  va_start(args, szFmt);
  _vstprintf_s(szBuf, BUFFER_MED_SIZE, szFmt, args);
  va_end(args);
}  

{
  char *foo = "foo"; 
  char *bar = "bar"; 
  LogToFile(_T("Test %hs %hs"), foo, bar); 
}