Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

char

tchar

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?

like image 783
Nick Bolton Avatar asked Oct 23 '09 12:10

Nick Bolton


2 Answers

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); 
}
like image 188
Remy Lebeau Avatar answered Oct 05 '22 22:10

Remy Lebeau


Usually it looks like the following:

char *foo = "foo";
char *bar = "bar";
#ifdef UNICODE
LogToFileW( L"Test %S %S", foo, bar); // big S
#else
LogToFileA( "Test %s %s", foo, bar);
#endif

Your question is not completely clear. How your function is implemented and how do you use it?

like image 30
Kirill V. Lyadvinsky Avatar answered Oct 05 '22 22:10

Kirill V. Lyadvinsky