1

I'm not familiar with C. How can I pass a C array to a Objective-C function ?

I actually need an example of a class function converting NSArray to C arrays. This is what I have so far:

+ (NSArray *)convertArray:(NSString*)array { //I don't think this is correct: the argument is just a NSString parameter and not an array

    NSMutableArray * targetArray = [NSMutableArray array];

    for (i = 0; i < SIZE; i++) //SIZE: I dunno how to get the size of a C array.
    {
        [targetArray addObject: [NSString stringWithString:array[i]];
    }
    return targetArray;
}
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
aneuryzm
  • 63,052
  • 100
  • 273
  • 488
  • Take a look at http://stackoverflow.com/questions/8086634/creating-a-nsarray-from-a-c-array and http://stackoverflow.com/questions/5150312/using-c-arrays-in-objective-c – Parag Bafna Jun 29 '12 at 08:35

1 Answers1

2

There are a few ways.

If your array size is fixed at compile-time, you can use the C99 static modifier:

-(void) doSomething:(NSString *[static 10]) arg
{

}

If not, you have to pass it as two separate arguments. One as a pointer to the first element of it, and the second as the length of it:

-(void) doSomething:(NSString **) arg count:(size_t) count
{

}

Now you can access your variables like any other array you may have.

Because you are dealing with a C-array of objective-c objects, you can actually use NSArray's built in constructor for turning a C-array into a NSArray:

NSArray *result = [NSArray arrayWithObjects:arg count:count];
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • How do I compute the array size? I Dont know the value to pass to the count parameter... – aneuryzm Jun 28 '12 at 15:33
  • But this method is used for arrays of different size. How do I get the array length in C ? – aneuryzm Jun 28 '12 at 22:33
  • C doesn't really have an array type, it has pointer types. So, how to determine the size is going to be dependent upon the code that you are interfacing with. Either there will be a zero termination (common for pointer arrays), another semaphore (-1 is common for arrays where people expect the contents to be 0 or greater), or a count (the most common approach). – gaige Jun 29 '12 at 14:51
  • `NSArray *result = [NSArray arrayWithObjects:arg count:count];`, where `arg` is the c array? – William GP Jul 18 '17 at 20:46