简体   繁体   中英

How can I convert an NSString to a CString in c++ without Obj-C code?

I am trying to get the current user name in c++ using the NSFullUserName function but it returns an NSString . Therefore, how can I convert an NSString to a CString in c++ without Obj-C code?

It is sheer silliness not to use Objective-C for this.

That said, you can cast an NSString * to a CFStringRef and use the CFString functions to get a C string. You will probably find the CFStringGetLength and CFStringGetCString functions and the kCFStringEncodingUTF8 constant useful. Keep in mind that many Unicode characters require more than one byte to represent in UTF-8.

NSString is toll-free bridged with CFString (ie, you can just cast the pointer — the thing it points to can be interpreted as either type), and you can manipulate CFString using vanilla C calls.

So you'd typically attempt CFStringGetCStringPtr to try to get a pointer directly to the NSString contents as a C string without any copying, then fall back on allocating a suitably sized C-style array and CFStringGetCString if the direct pointer isn't available (typically because the encoding you want doesn't match the NSString 's internal encoding).

CFStringGetMaximumSizeForEncoding will return the maximum size of buffer you need to allocate for a given encoding and string length, CFStringGetLength the length of a given string.

So eg

void Class::DoSomethingWithObjCString(NSString *objcString)
{
    CFStringRef string = (CFStringRef)objcString;

    const char *bytes = CFStringGetCStringPtr(string, kCFStringEncodingUTF8);

    if(bytes)
        DoSomethingWithUTF8String(bytes);
    else
    {
        size_t sizeToAllocate = 
                CFStringGetMaximumSizeForEncoding(
                     CFStringGetLength(string), kCFStringEncodingUTF8);

        char *allocatedBytes = new char[sizeToAllocate];

        CFStringGetCString(string, 
                           allocatedBytes, 
                           sizeToAllocate, 
                           kCFStringEncodingUTF8);
        DoSomethingWithUTF8String(allocatedBytes);

        delete[] allocatedBytes;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM