简体   繁体   中英

Unicode, char pointers and wcslen

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?

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.

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().

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM