我正在使用 CFDictionaryGetValue
从 CFDictionaryRef
中获取 CFStringRef
。
我一直在尝试使用 CFStringGetCString
或 CFStringGetCStringPtr
将 CFStringRef
转换为 char*
,他们要么返回 NULL,要么崩溃。
有没有办法做到这一点?怎么办?
谢谢。
编辑:示例代码:
SecStaticCodeRef staticCode;
CFDictionaryRef information;
SecCSFlags flags = kSecCSInternalInformation
| kSecCSSigningInformation
| kSecCSRequirementInformation
| kSecCSInternalInformation;
CFURLRef pathURL = NULL;
CFStringRef pathStr = NULL;
CFStringRef uniqueid;
char* str = NULL;
CFIndex length;
pathStr = CFStringCreateWithCString(kCFAllocatorDefault,
filename, kCFStringEncodingUTF8);
pathURL = CFURLCreateWithString(kCFAllocatorDefault, pathStr, NULL);
SecStaticCodeCreateWithPath(pathURL, kSecCSDefaultFlags, &staticCode);
SecCodeCopySigningInformation(staticCode, flags, &information);
uniqueid = (CFStringRef) CFDictionaryGetValue(information, kSecCodeInfoUnique);
// how do I convert it here to char *?
length = CFStringGetLength(uniqueid);
str = (char *)malloc( length + 1 );
CFStringGetCString(uniqueid, str, length, kCFStringEncodingUTF8);
printf("hash of signature is %s\n", str);
CFRelease(information);
CFRelease(staticCode);
最佳答案
来自第 17 章 example code在 iOS:PTL .
char * MYCFStringCopyUTF8String(CFStringRef aString) {
if (aString == NULL) {
return NULL;
}
CFIndex length = CFStringGetLength(aString);
CFIndex maxSize =
CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
char *buffer = (char *)malloc(maxSize);
if (CFStringGetCString(aString, buffer, maxSize,
kCFStringEncodingUTF8)) {
return buffer;
}
free(buffer); // If we failed
return NULL;
}
生成的缓冲区必须始终被释放(这就是名称中包含 Copy
的原因)。链接的示例代码还有一个速度稍快的版本,它使用您提供的缓冲区。
关于将 CFStringRef 转换为 char *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9166291/