Many Mac OS libraries have programming interfaces that require C strings or Pascal strings for some of their parameters. Four functions of String Services extracts the contents of CFStrings into these string buffer formats.
A common strategy for accessing the contents of CFStrings as either a C string or as a Pascal string is to first try to get a pointer of the appropriate type to these strings and, if that fails, to copy the contents into a local buffer. Listing 7 illustrates this strategy for C strings using the
CFStringGetCStringPtr
and
CFStringGetCString
functions.
Listing 7 Accessing CFString contents as a C string
CFStringRef str; CFRange rangeToProcess; const char *bytes; str = CFStringCreateWithCString(NULL, "Hello World", CFStringGetSystemEncoding()); bytes = CFStringGetCStringPtr(str, CFStringGetSystemEncoding()); if (bytes == NULL) { char localBuffer[10]; Boolean success; success = CFStringGetCString(str, localBuffer, 10, CFStringGetSystemEncoding()); }
The complementary functions for Pascal strings are
CFStringGetPascalStringPtr
and
CFStringGetPascalString
. All four of these functions allow you to specify the encoding that the Unicode characters should be converted to.
The functions that end with "Ptr" either return the desired pointer quickly, in constant time, or they return
NULL
. If the latter is the case, you should use either of the functions
CFStringGetPascalString
or
CFStringGetCString
.
The buffer for the
CFStringGetPascalString
or
CFStringGetCString
functions can either be on the stack or a piece of allocated memory. These functions might still fail to get the characterse, but that only happens in two circumstances: the conversion from the
UniChar
contents of CFString to the specified encoding fails or the buffer is too small. If you need a copy of the character buffer or if the code in question is that performance-sensitive, you could simply call the
CFStringGetPascalString
function or the
CFStringGetCString
function without even attempting to get the pointer first.