Created
November 8, 2019 16:34
-
-
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++.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 {}; | |
} |
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
It turns outCFStringGetMaximumSizeForEncoding
forkCFStringEncodingUTF8
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.