Xzhsh
Xzhsh

Reputation: 2239

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?

Upvotes: 0

Views: 5193

Answers (4)

rustyx
rustyx

Reputation: 85541

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.

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 598414

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

Upvotes: 1

Igor Zevaka
Igor Zevaka

Reputation: 76610

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.

Upvotes: 1

Dean Harding
Dean Harding

Reputation: 72688

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.

Upvotes: 0

Related Questions