我尝试在运行时从 const char*
创建新的 CFStringRef
,但 CFStringCreateWithCString
返回 null
code> 对于所有短于 10 个字符的字符串:
// Test w/ 9-character string
CFStringRef str1 = CFStringCreateWithCString(NULL, "123456789", kCFStringEncodingUTF8);
printf("str1: %p - %s\n", str1, CFStringGetCStringPtr(str1, kCFStringEncodingUTF8));
// Test w/ 10-character string
CFStringRef str2 = CFStringCreateWithCString(NULL, "0123456789", kCFStringEncodingUTF8);
printf("str2: %p - %s\n", str2, CFStringGetCStringPtr(str2, kCFStringEncodingUTF8));
以上示例的输出:
str1: 0x1ea1f72bb30ab195 - (null)
str2: 0x1005073e0 - 0123456789
如您所见,第一个字符串(由 9 个字符组成)返回 null
,而第二个字符串(10 个字符)则正常。
我做了一些测试,似乎 CFStringCreateWithCString
对于所有超过 10 个字符的字符串都可以正常工作,但对于 9 个或更少字符的字符串总是返回 null
。
什么可能导致此行为以及如何修复它?
最佳答案
CFStringCreateWithCString
对于这两个字符串都可以正常工作。 CFStringGetCStringPtr
的文档说:
Quickly obtains a pointer to a C-string buffer containing the characters of a string in a given encoding.
This function either returns the requested pointer immediately, with no memory allocations and no copying, in constant time, or returns NULL. If the latter is the result, call an alternative function such as the CFStringGetCString function to extract the characters.
Whether or not this function returns a valid pointer or NULL depends on many factors, all of which depend on how the string was created and its properties. In addition, the function result might change between different releases and on different platforms. So do not count on receiving a non-NULL result from this function under any circumstances.
关于CFStringCreateWithCString 对于少于 10 个字符的字符串返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43550653/