次の方法で共有


Some funky wchar allocation hacks in ANSI C

So I've been dusting some wide character string programming spiderwebs out of the programming attic lately and I remembered a few funky hacks that I have used before.

First, let me describe the problem that I've been approaching where I needed to use wide character strings.  I was writing code for a porting kit where I did not have access to a library for creating wide character strings.  I wanted to create a string to pass to wprintf to be used for tracing. If I were doing this in Windows, I would simply allocate them like this:

wchar_t* rgwchSomeString = L"wide character string";

The only thing was, I did not have the luxury of libraries that supported this and so I came up with this hacky way of specifiying wide character strings using a cast to a character string:

wchar_t *rgwchSomeString = (wchar_t*)"s\0o\0m\0e\0 \0w\0i\0d\0e\0 \0c\0h\0a\r\0\s\0\0\0";

After some discussions with testers and developers, I've come to the conclusion that this makes too many assumptions on the format of the wide characters.  It would be better to create a macro that is aware of the endianness of the wide character string. By using this macro, you would be able to create a piece of "more portable" code.

At any rate, I thought the wide character string hack was fun so I'm sharing it.  It certainly is useful for traces, but I would never use it in "real" code of any sort.