gpt4 book ai didi

将 CFStringRef 转换为 char *

转载 作者:太空狗 更新时间:2023-10-29 16:31:26 34 4
gpt4 key购买 nike

我正在使用 CFDictionaryGetValueCFDictionaryRef 中获取 CFStringRef

我一直在尝试使用 CFStringGetCStringCFStringGetCStringPtrCFStringRef 转换为 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 codeiOS: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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com