I write a piece of code which uses both c++ and Objective C.
I need to convert NSString*
to char*
. [str UTF8string]
wouldn't work because it returns const char*
. I know:
std::string
-> char*
: char* c = const_cast<char*>(pathStr.c_str());
NSString*
-> std::string
: link
But it looks too strange and I still can't verify it. Can I convert it in a better way, for example, NSString*
-> const char*
-> char*
Cast it to a char*
(char*)[str UTF8String];
As long as you don't want to edit it... if you do then strcpy it into some char array.
I guess it just depends on what you want to do with it.
Note this:
The returned C string is a pointer to a structure inside the string object, which may have a lifetime shorter than the string object and will certainly not have a longer lifetime. Therefore, you should copy the C string if it needs to be stored outside of the memory context in which you called this method.
If you plan to modify the string, or if you plan to use it for an extended period of time, do the appropriate copy operation on it. Or use getCString:maxLength:encoding:
to directly create the copy.
If you don't plan to modify the string then there's in theory no need to cast to non-const (though it is true that many interfaces call for a char*
parm when they should call for const char*
, so sometimes you have to cheat).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With