4

I need to call a cpp function like

void myFunc(float **array2D, int rows, int cols)
{
}

within an objective-c object. Basically, the array is created in my objective-c code as I create an NSArray object. Now, the problem is how to pass this array to my cpp function.

I am a bit new to these mixed c++/objective-c stuffs so any hint will be highly appreciated.

Thanks

3
  • 1
    The answers so far assume array2D is unidimensional. Can you confirm that? I’m guessing it’s a bidimensional array since the parameter is float **array2D, but I could be wrong. Commented Jan 28, 2011 at 23:57
  • 1
    if you are using c++, why not using std::vector's ? you would not need to send the side of the matrix. void myFunc(std::vector<std::vector<float> > array2D){...code...} Commented Jan 29, 2011 at 0:11
  • my array is bidimensional but it doesnt matter here as I am trying to convert NSArray of NSArray to float **. Still the objective is to convert NSArray -> float * Commented Jan 30, 2011 at 19:22

3 Answers 3

8

I guess you have to convert the NSArray to a plain C array. Something like:

NSArray *myNSArray; // your NSArray

int count = [myNSArray count];
float *array = new float[count];
for(int i=0; i<count; i++) {
    array[i] = [[myNSArray objectAtIndex:i] floatValue];
}

or, as a commenter suggested (assuming your NSArray contains NSNumbers):

NSArray *myNSArray; // your NSArray

int count = [myNSArray count];
float *array = new float[count];
int i = 0;
for(NSNumber *number in myNSArray) {
    array[i++] = [number floatValue];
}
Sign up to request clarification or add additional context in comments.

1 Comment

instead of the for statement, I would use for (NSString *element in array) {... code ...}. using an enumeration is faster, and you save a few variable declaration. but your answer is good :)
2

Look at this post.

Check out the answer that mentions using [NSArray getObjects] to create a c-style array.

Here's the code that the poster put in there:

NSArray *someArray = /* .... */;
NSRange copyRange = NSMakeRange(0, [someArray count]);
id *cArray = malloc(sizeof(id *) * copyRange.length);

[someArray getObjects:cArray range:copyRange];

/* use cArray somewhere */

free(cArray);

1 Comment

But OP’s function expects an array of float, so this method is not really applicable.
0

Alternately, since CFArray is toll-free bridged to NSArray, could you call those C functions from your C++ function? I'd look around, wouldn't be surprised if there weren't a C++ wrapper to give similar semantics, or one could be written easily enough.

Comments

Your Answer

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.