Re: NSString to const char
Re: NSString to const char
- Subject: Re: NSString to const char
- From: Steve Christensen <email@hidden>
- Date: Mon, 26 May 2008 08:02:37 -0700
On May 26, 2008, at 6:47 AM, Micha Fuhrmann wrote:
I need to pass a const char to a C++ function from an NSString.
However the argument I pass end up as garbage and that's it. Here
an example to illustrate:
NSString* theNsstring = @"étape";
My understanding is that NSString (and CFStringRef) string constants
can only use 7-bit ASCII characters, so the first character ('é') may
not be encoded as you expect. I wrote a small test program with your
two lines of code, except that I replaced the constant string, above,
with:
const char* theCString = "étape";
NSString* theNsstring = [NSString stringWithCString:theCString
encoding:NSUTF8StringEncoding];
since it turns out that the C string was being encoded as utf8.
const char* theConstString = [theNsstring
cStringUsingEncoding:NSUnicodeStringEncoding];
In the console theConstString ends up as "\xe9".
That's understandable since NSUnicodeStringEncoding consists of 2-
byte unichars, even though you're treating them as chars. When I
dumped out the individual characters, this is what I got for various
encodings:
é---- t- a- p- e-
original C string (utf8): c3 a9 74 61 70 65
é---- t---- a---- p---- e----
NSUnicodeStringEncoding: e9 00 74 00 61 00 70 00 65 00
é---- t- a- p- e-
NSUTF8StringEncoding: c3 a9 74 61 70 65
é- t- a- p- e-
NSMacOSRomanStringEncoding: 8e 74 61 70 65
As you can see, when using the NSUnicodeStringEncoding encoding you
get a null-terminator after the 0xe9 character, which is what you
were seeing. A better encoding would be NSUTF8StringEncoding (or even
NSMacOSRomanStringEncoding, depending on what's consuming your C
string).
steve
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden