Convert from CFURLRef or CFStringRef to std::string

3ef9g picture 3ef9g · Mar 4, 2015 · Viewed 10k times · Source

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?

Answer

Michael Dautermann picture Michael Dautermann · Mar 4, 2015

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