CFStringCreateWithCString 对于少于 10 个字符的字符串返回 null

标签 c core-foundation cfstring

我尝试在运行时从 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/

相关文章:

c - C中如何实现函数重载?

c - 警告 : cast from pointer to integer of different size [-Wpointer-to-int-cast]

c - 初学者 C 代码 - 二维数组的问题

c++ - 为什么我的 CFRunLoopTimer 没有触发?

c++ - Core Foundation 为每次调用 CFSTR() 创建内存泄漏

c - 在包含字符串的结构上使用 qsort

ios - 无法识别的选择器发送到实例 _UIAlertControllerAlertPresentationController

ios - Swift 中的 CFDictionaryRef 问题

c# - 如何在 C# 中将字符串转换为 cfstring

ios7 - CFStringGetCStringPtr 在 iOS7 上返回 NULL