Skip to content

Instantly share code, notes, and snippets.

@peter-bloomfield
Created November 8, 2019 16:34
Show Gist options
  • Save peter-bloomfield/1b228e2bb654702b1e50ef7524121fb9 to your computer and use it in GitHub Desktop.
Save peter-bloomfield/1b228e2bb654702b1e50ef7524121fb9 to your computer and use it in GitHub Desktop.
A function to convert a CFString (macOS / OS X) to a UTF-8 std::string in C++.
#include <CoreFoundation/CoreFoundation.h>
#include <string>
#include <vector>
/**
* Converts a CFString to a UTF-8 std::string if possible.
*
* @param input A reference to the CFString to convert.
* @return Returns a std::string containing the contents of CFString converted to UTF-8. Returns
* an empty string if the input reference is null or conversion is not possible.
*/
std::string cfStringToStdString(CFStringRef input)
{
if (!input)
return {};
// Attempt to access the underlying buffer directly. This only works if no conversion or
// internal allocation is required.
auto originalBuffer{ CFStringGetCStringPtr(input, kCFStringEncodingUTF8) };
if (originalBuffer)
return originalBuffer;
// Copy the data out to a local buffer.
auto lengthInUtf16{ CFStringGetLength(input) };
auto maxLengthInUtf8{ CFStringGetMaximumSizeForEncoding(lengthInUtf16,
kCFStringEncodingUTF8) + 1 }; // <-- leave room for null terminator
std::vector<char> localBuffer(maxLengthInUtf8);
if (CFStringGetCString(input, localBuffer.data(), maxLengthInUtf8, maxLengthInUtf8))
return localBuffer.data();
return {};
}
@alxarsenault
Copy link

if (CFStringGetCString(input, localBuffer.data(), maxLengthInUtf8, kCFStringEncodingUTF8))
and not
if (CFStringGetCString(input, localBuffer.data(), maxLengthInUtf8, maxLengthInUtf8))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment