20090726

C string to CFString

I have a null-terminated string of (random) ASCII chars that I need to convert to a CFString for an API call. However, the following call yields NULL:

CFStringRef convertedValue = CFStringCreateWithCString(kCFAllocatorDefault, c_string, kCFStringEncodingUTF8);

According to the doc, this means "there was a problem creating the object."
I am currently stumped as to why.

2 comments:

  1. Maybe the string was in fact Latin1 (0-255), not ASCII (0-127), and since Latin1 is not valid UTF8, the decoding from UTF8 failed on first Latin1 character. Are you sure there is no copyright sign or euro sign or whatever in the string? Or if the characters are truly random, are you making sure they are ASCII, i.e. 0-127 only (setting the highest char bit to 0)? Just a thought. Maybe try with kCFStringEncodingLatin1, if that does not fail, than it's as I said.

    And sorry for making this comment under the wrong (Core Foundation meets C++) post at first :-) Feel free to delete that comment there.

    ReplyDelete
  2. Thanks for the suggestion and sorry it took me so long to see it. What I ended up doing is creating a static array of allowed chars ([A-Za-z0-9_]) and randomizing from [0-LengthOfAllowedCharArray) for each char I want in the buffer.

    ReplyDelete