Tutorial :Unicode, char pointers and wcslen



Question:

I've been trying to use the cpw library for some graphics things. I got it set up, and I seem to be having a problem compiling. Namely, in a string header it provides support for unicode via

#if defined(UNICODE) | defined(_UNICODE)  #define altstrlen wstrlen  #else  #define altstrlen strlen  

Now, there's no such thing as wstrlen on Windows afaik, so I tried changing that to wcslen, but now it gives me and error because it tried to convert a char * to a wchar_t *. I'm kinda scared that if I just had it use strlen either way, something else would screw up.

What do you think stackoverflow?


Solution:1

Maybe you can define wcslen as wstrlen before including the lib header:

#define wstrlen wcslen  #include "cpw.h"  

The error you are getting is likely to be due to you passing a char* that into something that ends up calling one of those functions.


Solution:2

If your data is char* based to begin with, then there is no need to call a Unicode version of strlen(), just use the regular strlen() by itself, since it takes char* as input. Unless your char* data is actually UTF-8 encoded and you are trying to determine the unencoded Unicode length, in which case you need to decode the UTF-8 first before then calling wcslen().


Solution:3

If you're using Unicode on Windows, you need to change all of your character types to wchar_t. That means, instead of:

char *str = "Hello World";  int len = strlen(str);  

You need:

wchar_t *str = L"Hello World";  int len = wcslen(str);  

Notice that the character type has been changed to wchar_t and the string literal is prefixed with L.


Solution:4

Visual Studio already has such macros, see tchar.h.

#include <tchar.h>    TCHAR *str = _T("Sample text");  int len = _tcslen(str);  

-- will work in ANSI, MBCS and UNICODE mode depending on compiler settings.

For more details see this article.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »