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
123k23 gold badges219 silver badges249 bronze badges
asked Jun 28, 2012 at 14:55
1

1 Answer 1

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];
answered Jun 28, 2012 at 14:58
Sign up to request clarification or add additional context in comments.

4 Comments

How do I compute the array size? I Dont know the value to pass to the count parameter...
But this method is used for arrays of different size. How do I get the array length in C ?
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).
NSArray *result = [NSArray arrayWithObjects:arg count:count];, where arg is the c array?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.