将 CFStringRef 转换为 char *

标签 c macos

我正在使用 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/

相关文章:

c++ - OSX以最小的延迟将像素推向屏幕

objective-c - 获取桌面上存在的图标和文件的详细信息及其在桌面上的位置?

c - 为什么我的 C 程序没有按预期释放内存?

ps命令的C代码

c - 如何在 ROM 中存储常量 (Atmel)

python - 使用 conda 安装 flask-mysql

python - Django/PIL 错误 - 呈现 : The _imagingft C module is not installed 时捕获异常

c - 使用 const 变量初始化数组

c - 我不明白他想要什么

c - 堆栈函数删除C中的结束函数