c++macosstdstringcfstringcfurl-encoding

Convert from CFURLRef or CFStringRef to std::string


How can I convert a CFURLRef to a C++ std::string?

I also can convert from the CFURLRef to a CFStringRef by:

CFStringRef CFURLGetString ( CFURLRef anURL );

But now I have the same problem. How can I convert the CFStringRef to a std::string?


Solution

  • A CFStringRef is toll free bridged to a NSString object, so if you're using Cocoa or Objective C in any way, converting is super simple:

    NSString *foo = (NSString *)yourOriginalCFStringRef;
    std::string *bar = new std::string([foo UTF8String]);
    

    More detail can be found here.

    Now, since you didn't tag this question with Cocoa or Objective-C, I'm guessing you don't want to use the Objective-C solution.

    In this case, you need to get the C string equivalent from your CFStringRef:

    const CFIndex kCStringSize = 128; 
    char temporaryCString[kCStringSize];
    bzero(temporaryCString,kCStringSize);
    CFStringGetCString(yourStringRef, temporaryCString, kCStringSize, kCFStringEncodingUTF8);
    std::string *bar = new std::string(temporaryCString);
    

    I didn't do any error checking on this code and you may need to null terminate the string fetched via CFStringGetCString (I tried to mitigate that by doing bzero).