Skip to content

Instantly share code, notes, and snippets.

@peter-bloomfield
Created November 8, 2019 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 {};
}
@dbwiddis
Copy link

dbwiddis commented Apr 25, 2021

It turns out CFStringGetMaximumSizeForEncoding for kCFStringEncodingUTF8 only multiplies by 3, so this fails if the string is entirely 4 byte unicode characters like 💩.
It turns out all 4-byte UTF-8 characters are at least 4-byte/2-code-pair Unicode characters so this does work.

@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