我正在使用CFStringRef一个.CFDictionaryRefCFDictionaryGetValue
我一直在尝试将其转换CFStringRef为char*使用CFStringGetCString或者CFStringGetCStringPtr它们返回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);
Run Code Online (Sandbox Code Playgroud)
Rob*_*ier 24
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;
}
Run Code Online (Sandbox Code Playgroud)
必须始终释放生成的缓冲区(这就是Copy名称中的原因).链接的示例代码也有一个稍快的版本,使用您提供的缓冲区.
bob*_*obo 11
另一个答案:
const char *cs = CFStringGetCStringPtr( cfString, kCFStringEncodingMacRoman ) ;
puts( cs ) ; // works
Run Code Online (Sandbox Code Playgroud)
我找不到kCFStringEncodingUTF8给出NULL 的原因,但 kCFStringEncodingMacRoman似乎工作正常.
针对同一问题还有另一种解决方案:
char * myCString = [(__bridge NSString *)myCfstring UTF8String];
Run Code Online (Sandbox Code Playgroud)
快乐编码:)
| 归档时间: |
|
| 查看次数: |
26000 次 |
| 最近记录: |