Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString* to char*?

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*

like image 973
user2083364 Avatar asked Jan 03 '14 15:01

user2083364


2 Answers

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.

like image 63
0xFADE Avatar answered Sep 18 '22 13:09

0xFADE


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).

like image 31
Hot Licks Avatar answered Sep 17 '22 13:09

Hot Licks