1

In an iOS app, I'm using a 3rd party SDK written in C. As a result of an SDK method call I receive an unsigned char array (see example below).

I need to convert this array to an Objective-C String (NSString) as to save it and later on convert it back to C to pass it as a parameter to another SDK method.


I've seen multiple ways to convert a C string to Objective-C.

NSString *example1 = [NSString stringWithFormat:@"%s", myArray]; // "8oFDO{c."rägÕªö"
NSString *example2 = [[NSString alloc] initWithBytes:myArray length:sizeof(myArray) encoding:NSASCIIStringEncoding]; // "8oFDO{c."rägÕªö"
...

But none of them seems to allows \0 (null-terminating character) in the middle (see [29] in the example below).


Example unsigned char array response:

{
  [0] = '8'
  [1] = '\b'
  [2] = '\x01'
  [3] = 'o'
  [4] = '\x01'
  [5] = '\x03'
  [6] = 'F'
  [7] = 'D'
  [8] = 'O'
  [9] = '\x02'
  [10] = '\x10'
  [11] = '\x0e'
  [12] = '{'
  [13] = '\x8d'
  [14] = 'c'
  [15] = '.'
  [16] = '\x19'
  [17] = '"'
  [18] = 'r'
  [19] = '\xe4'
  [20] = 'g'
  [21] = '\x18'
  [22] = '\xd5'
  [23] = '\xaa'
  [24] = '\xf6'
  [25] = '\x95'
  [26] = '\x18'
  [27] = '\x03'
  [28] = '\x01'
  [29] = '\0'
  [30] = '\x04'
  [31] = '\x01'
  [32] = '\x05'
  [33] = '\x05'
  [34] = '\x01'
  [35] = '\x05'
  [36] = '\x06'
  [37] = '\x01'
  [38] = '\x01'
  ...
}

How can I convert from C to Objective-C and then back from Objective-C to C?

Yonic Surny
  • 451
  • 6
  • 15
  • https://stackoverflow.com/questions/3949628/convert-nsdata-to-nsstring-and-ignore-null-bytes ? But you'll lose the fact that `byte[29]` has a `\0` (if you want to convert it back), so just save the bytes array? – Larme Jun 20 '17 at 14:19
  • I see other solutions like https://stackoverflow.com/a/6093939/1197572 replacing `\0` with `\\0`. – Yonic Surny Jun 20 '17 at 14:36
  • 4
    this `unsigned char` array doesn't sims to be a string at all. You should handle it as if it is `void *` and use NSData to store such arguments. – toma Jun 20 '17 at 14:38
  • @AndrewTomenko you might be onto something, by storing it into an NSData and converting it back to unsigned char array I get the same result as the initial value which is promising. I can't test further today, but I'll do that tomorrow and report back the result. Thank you :-) – Yonic Surny Jun 20 '17 at 14:58
  • @AndrewTomenko got it to work. Thanks for the insight! – Yonic Surny Jun 21 '17 at 19:49

1 Answers1

1

This unsigned char array doesn't sims to be a string at all. You should handle it as if it is void * and use NSData to store such arguments.

toma
  • 1,471
  • 12
  • 20