From e618303343ce84499665d45d2460f3fec42dd21f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=80=9A=E6=B4=B2?= Date: Tue, 12 Nov 2024 21:52:12 +0800 Subject: [PATCH] Media (macOS): try fixing error `CFStringGetCString() failed` --- src/util/apple/cf_helpers.c | 17 ++++++++++++----- tests/strbuf.c | 3 +++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/util/apple/cf_helpers.c b/src/util/apple/cf_helpers.c index a0bc534c7..a7705ec65 100644 --- a/src/util/apple/cf_helpers.c +++ b/src/util/apple/cf_helpers.c @@ -49,15 +49,22 @@ const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result) if (CFGetTypeID(cf) == CFStringGetTypeID()) { CFStringRef cfStr = (CFStringRef)cf; - uint32_t length = (uint32_t)CFStringGetLength(cfStr); - //CFString stores UTF16 characters, therefore may require larger buffer to convert to UTF8 string - ffStrbufEnsureFree(result, length * 2); - if (!CFStringGetCString(cfStr, result->chars, result->allocated, kCFStringEncodingUTF8)) + + const char* cstr = CFStringGetCStringPtr(cfStr, kCFStringEncodingUTF8); + if (cstr) { - ffStrbufEnsureFree(result, length * 4); + ffStrbufSetS(result, cstr); + return NULL; + } + else + { + uint32_t length = CFStringGetLength(cfStr); + uint32_t maxLength = (uint32_t) CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8); + ffStrbufEnsureFixedLengthFree(result, maxLength); if(!CFStringGetCString(cfStr, result->chars, result->allocated, kCFStringEncodingUTF8)) return "CFStringGetCString() failed"; } + // CFStringGetCString ensures the buffer is NUL terminated // https://developer.apple.com/documentation/corefoundation/1542721-cfstringgetcstring result->length = (uint32_t) strnlen(result->chars, (uint32_t)result->allocated); diff --git a/tests/strbuf.c b/tests/strbuf.c index 7d016467e..92141d4b9 100644 --- a/tests/strbuf.c +++ b/tests/strbuf.c @@ -381,6 +381,9 @@ int main(void) ffStrbufEnsureFixedLengthFree(&strbuf, 10); VERIFY(strbuf.length == 0); VERIFY(strbuf.allocated == 11); + ffStrbufEnsureFixedLengthFree(&strbuf, 12); + VERIFY(strbuf.length == 0); + VERIFY(strbuf.allocated == 13); ffStrbufDestroy(&strbuf); //ffStrbufEnsureFixedLengthFree / empty buffer with zero free length