2007/01/29

Conversion Between "char*" And "unsigned char*"

C++ says that one of the function of reinterpret_cast is

A pointer to an object can be explicitly converted to
a pointer to an object of different type.
and
Plain char, signed char, and unsigned char are three distinct types.
in ISO/IEC14882:2003.

Hence, as the type of string literal is const char*, following code can not be compiled in C++.

unsigned char* message = "Hello, the World.";
In this case, the code requires reinterpret_cast<unsigned char*>(foo) or static_cast<unsigned char*>(static_cast<void*>(foo)) to convert from unsigned char* to char*.

In addition, the code requires const_cast because standard conversion from const char* to char* does not apply with this case from const unsigned char* to unsigned char*.

Such casts are so dirty.

Some compilers such as VC7.1 have the option which makes literals to unsigned. But that is not standard C++ but implementation-extension.

C++ also says

A char, a signed char, and an unsigned char occupy the same
amount of storage and have the same alignment requirements.
So the conversion between unsigned char* and char* are normally safe. Hence, I think that double static_cast are well-formed. But, I wraps the casts as string_cast, because the double static_cast are too long.

string_cast sample excepted const_cast is following


template<typename OUT> OUT* string_cast(unsigned char* str);
template<typename OUT> OUT* string_cast(char* str);
template<> inline unsigned char* string_cast(char* str)
{ return static_cast<unsigned char*>(static_cast<void*>(str)); }
template<> inline char* string_cast(unsigned char* str)
{ return static_cast<char*>(static_cast<void*>(str)); }

For example, char* str and unsigned char* ustr are defined previously,
str = string_cast<char>(ustr);
or ustr = string_cast<unsinged char>(str); are fine.

How to set parameters to debugging program on Visual Studio 2019 with CMake

Solution: MSDN Sometimes the "Debug and Launch Settings for CMake" bottun is disabled. In this case, change to the target view. ...