Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing NSArray to a cpp function

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

like image 995
Abbas Avatar asked Jan 20 '23 15:01

Abbas


1 Answers

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];
}
like image 127
ySgPjx Avatar answered Jan 31 '23 09:01

ySgPjx