Skip to content

Commit 3aafc0e

Browse files
committed
CFStringRef to std::string function
1 parent 2be12d1 commit 3aafc0e

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

source/StringExtras.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,22 @@ namespace vx {
5454

5555
return stringLeftTrim( stringRightTrim( _string, _trim.empty() ? trimmed : _trim ), _trim.empty() ? trimmed : _trim );
5656
}
57+
58+
#ifdef __APPLE__
59+
std::string fromCFStringRef( CFStringRef _stringRef ) {
60+
61+
if ( auto fastCString = CFStringGetCStringPtr( _stringRef, kCFStringEncodingUTF8 ) ) {
62+
63+
return std::string( fastCString );
64+
}
65+
66+
auto utf16length = CFStringGetLength( _stringRef );
67+
auto maxUtf8len = CFStringGetMaximumSizeForEncoding( utf16length, kCFStringEncodingUTF8 );
68+
69+
std::string converted( static_cast<std::size_t>( maxUtf8len ), '\0' );
70+
CFStringGetCString( _stringRef, converted.data(), maxUtf8len, kCFStringEncodingUTF8 );
71+
converted.resize( std::strlen( converted.data() ) );
72+
return converted;
73+
}
74+
#endif
5775
}

source/StringExtras.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@
2828
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2929
*/
3030

31+
/* apple header */
32+
#ifdef __APPLE__
33+
#include <CoreFoundation/CoreFoundation.h>
34+
#endif
35+
3136
/* stl header */
3237
#include <string>
3338

@@ -44,4 +49,8 @@ namespace vx {
4449
// trim from both ends of string (right then left)
4550
std::string &stringTrim( std::string &_string,
4651
const std::string &_trim = {} );
52+
53+
#ifdef __APPLE__
54+
std::string fromCFStringRef( CFStringRef _stringRef );
55+
#endif
4756
}

0 commit comments

Comments
 (0)