aneuryzm
aneuryzm

Reputation: 64834

How can I pass a C array to a objective-C function?

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;
}

Upvotes: 1

Views: 1899

Answers (1)

Richard J. Ross III
Richard J. Ross III

Reputation: 55543

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];

Upvotes: 2

Related Questions