I am getting a CFStringRef
out of a CFDictionaryRef
using CFDictionaryGetValue
.
I've been trying to convert the CFStringRef
to a char*
using CFStringGetCString
or CFStringGetCStringPtr
and they either return a NULL or it crashes.
Is there a way to do this? How?
Thank you.
EDIT: sample code:
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);
From the Chapter 17 example code in 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;
}
The resulting buffer must always be freed (which is why Copy
is in the name). The linked example code also has a slightly faster version that uses a buffer you provide.
Another answer:
const char *cs = CFStringGetCStringPtr( cfString, kCFStringEncodingMacRoman ) ;
puts( cs ) ; // works
I can't find the reason why kCFStringEncodingUTF8
gives NULL, but kCFStringEncodingMacRoman
seems to work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With