String Services offers a pair of functions similar to those for C and Pascal strings for accessing the contents of a CFString as a 16-bit Unicode buffer:
CFStringGetCharactersPtr
and
CFStringGetCharacters
. The typical usage of these functions is also identical: you first optionally try to get a pointer to the characters and, if that fails, you try to copy the characters to a buffer you provide. These functions are different, however, in that they require a parameter specifying the length of the string.
Listing 8 illustrates the common strategy for using these functions.
Listing 8 Accessing CFString contents as Unicode characters
CFStringRef str; const UniChar *chars; str = CFStringCreateWithCString(NULL, "Hello World", CFStringGetSystemEncoding()); chars = CFStringGetCharactersPtr(str); if (chars == NULL) { CFIndex length = CFStringGetLength(str); UniChar *buffer = malloc(length * sizeof(UniChar)); CFStringGetCharacters(str, CFRangeMake(0, length), buffer); // Process the characters... free(buffer); }
This example shows an allocated buffer (
malloc
) rather than a stack buffer. You can use one or the other. Because you need to know the size of the buffer for the
CFStringGetCharacters
function, allocating memory is easier to do but is less efficient. If you allocate memory for the characters you must, of course, free the buffer when you no longer need it.