views:

671

answers:

1

I understand the difference between unsigned char * and char * types. I also understand how to use reinterpret_cast to cast an unsigned char * to a char * in C++.

I'm using sqlite3 in Objective-C and am trying to get an NSString from a call to

sqlite3_column_text(...);

To do this, I'm basically doing:

char *cParam = (char *)sqlite3_column_text(compiledStatementPtr, 0);
NSString *aParam = nil;
if (cParam) {
    aParam = [NSString stringWithUTF8String:cParam];
}

sqlite3_column_text(), however, returns an unsigned char * and I'm worried about the behavior of the cast to char *. I've read that the cast is implemenation specific and I was wondering if this is a safe cast in Objective-C or if I'm totally barking up the wrong tree?

+4  A: 

You don't have much to worry about due to the cast. Actually, Apple sample code uses the exact same code pattern you are using:

self.title =
  [NSString stringWithUTF8String:(char *)sqlite3_column_text(init_statement, 0)];

(From SQLite Book List Book.m class).

I think you should be more concerned with the database actually having UTF-8 strings.

notnoop
"I think you should be more concerned with the database actually having UTF-8 strings." Yes, the idea of char is pratically meanless today. If all of these APIs and types were being redone today we probably wouldn't have types with misleading names like char instead we'd just have uint8_t. All NSString cares about are the values of the bytes pointed at by the return value of sqlite3_column_text. Casting the pointer won't change the value of the bytes. You could cast the pointer to something rediculous like (NSRect *), and get a compiler warning, but the code would still function correctly.
Jon Hess