Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a CFStringRef to char *

Tags:

c

macos

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);
like image 682
Mr Aleph Avatar asked Feb 06 '12 19:02

Mr Aleph


2 Answers

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.

like image 142
Rob Napier Avatar answered Nov 07 '22 13:11

Rob Napier


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.

like image 15
bobobobo Avatar answered Nov 07 '22 12:11

bobobobo