views:

42

answers:

4

I have a wide-character XML message that I need to send over a Win32 socket in C++.

TCHAR wszBuffer[1024];

Should I sprintf(szSendBuffer, "%S", wszBuffer) the wide character buffer to a char array before sending it?

What is the correct way to send this?

A: 

You can simply cast it to a char*. On the other end you can simply cast the recieved buffer to wchar_t*.

David Feurle
`sizeof` is always in bytes, not count of elements, so the expression you show is wrong.
Ben Voigt
you are right - changed my answer
David Feurle
+1  A: 

Pass wszBuffer directly to the socket function, casting it to char*, with length = sizeof(wszBuffer), or 1024 * sizeof(TCHAR). In this case the buffer will be send as is.

If you want to send this text as ANSI string, convert it by any string convertion function. sprintf is OK, another way is W2A. But some information may be lost.

Alex Farber
I don't control the receiving end, which is a Java TCP server. If I simply cast it, won't this affect the characters read by their stream and parsed as XML?
FreshCode
If receiver expects ANSI string, you need to convert it to ANSI. If receiver expects Unicode string, just send it as byte stream. Of course, it must be the same on both ends.
Alex Farber
+1  A: 

Since you are dealing with XML, you need to encode it in UTF-8 or other XML-friendly character encoding (and specify that encoding in the XML's prolog) before sending it over the socket.

Remy Lebeau - TeamB
+1  A: 

Use WideCharToMultiByte to convert it to UTF-8 (or any other char-based encoding, as long as you declare it in the XML file).

dan04