简体   繁体   English

Unicode,char指针和wcslen

[英]Unicode, char pointers and wcslen

I've been trying to use the cpw library for some graphics things. 我一直在尝试将cpw库用于某些图形处理。 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 即,在字符串标头中,它通过提供对unicode的支持

#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 *. 现在,在Windows afaik上没有wstrlen这样的东西,所以我尝试将其更改为wcslen,但是现在它给了我一个错误,因为它试图将char *转换为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? 您如何看待stackoverflow?

Maybe you can define wcslen as wstrlen before including the lib header: 也许可以在包含lib标头之前将wcslen定义为wstrlen

#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. 您收到的错误很可能是由于您将char*传递给某些东西而最终调用了其中一个函数。

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. 如果您的数据是基于char *开头的,则无需调用Unicode版本的strlen(),只需单独使用常规的strlen(),因为它将char *作为输入。 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(). 除非您的char *数据实际上是UTF-8编码的,并且您试图确定未编码的Unicode长度,否则在这种情况下,您需要先解码UTF-8,然后再调用wcslen()。

Visual Studio already has such macros, see tchar.h . Visual Studio已经有这样的宏,请参见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. -将根据编译器设置在ANSI,MBCS和UNICODE模式下工作。

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 . 如果在Windows上使用Unicode,则需要将所有字符类型都更改为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 . 注意,字符类型已更改为wchar_t ,并且字符串文字以L为前缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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