How to cast const char * to unsigned char * ?
-
Take the function
void foo(unsigned char * param)
. It does not change the value of the string (it's a Win32 API function, don't ask me why it's not const). Now i'd like to pass it the value ofstd::string MyString
. I do this liek thatfoo(reinterpret_cast<unsigned char *>(MyString.c_str()));
but this can hardly be the recommended way (it works, but it's bad). Any suggestions anyone ?
-
Take the function
void foo(unsigned char * param)
. It does not change the value of the string (it's a Win32 API function, don't ask me why it's not const). Now i'd like to pass it the value ofstd::string MyString
. I do this liek thatfoo(reinterpret_cast<unsigned char *>(MyString.c_str()));
but this can hardly be the recommended way (it works, but it's bad). Any suggestions anyone ?
why not the simple
static_cast
? i can't see anything wrong otherwise...
You don't know where to start ? ask a good friend
-
why not the simple
static_cast
? i can't see anything wrong otherwise...
You don't know where to start ? ask a good friend
static_cast gives a compiler error:
error C2440: 'static_cast' : cannot convert from 'const char *' to 'unsigned char *'
-
static_cast gives a compiler error:
error C2440: 'static_cast' : cannot convert from 'const char *' to 'unsigned char *'
hum, yes, that's right (i have no compiler with me at the moment...). does it work without any explicit cast ?
You don't know where to start ? ask a good friend
-
Take the function
void foo(unsigned char * param)
. It does not change the value of the string (it's a Win32 API function, don't ask me why it's not const). Now i'd like to pass it the value ofstd::string MyString
. I do this liek thatfoo(reinterpret_cast<unsigned char *>(MyString.c_str()));
but this can hardly be the recommended way (it works, but it's bad). Any suggestions anyone ?
You want const_cast.
Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog
-
static_cast gives a compiler error:
error C2440: 'static_cast' : cannot convert from 'const char *' to 'unsigned char *'
You cannot cast a 'const' value to a 'non-const' because that's the whole point of the 'const' keyword. In this case you have to make a copy of the string and provide the second function with the copy. -- Roger
"It's supposed to be hard, otherwise anybody could do it!" - selfquote
"No one remembers a coward!" - Jan Elfström 1998
"...but everyone remembers an idiot!" - my lawyer 2005 when heard of Jan's saying above