[英]Passing NSArray to a cpp function
I need to call a cpp function like 我需要调用一个cpp函数
void myFunc(float **array2D, int rows, int cols)
{
}
within an objective-c object. 在objective-c对象中。 Basically, the array is created in my objective-c code as I create an NSArray object.
基本上,当我创建NSArray对象时,数组是在我的objective-c代码中创建的。 Now, the problem is how to pass this array to my cpp function.
现在,问题是如何将此数组传递给我的cpp函数。
I am a bit new to these mixed c++/objective-c stuffs so any hint will be highly appreciated. 我对这些混合c ++ / objective-c的东西有点新,所以任何提示都会受到高度赞赏。
Thanks 谢谢
I guess you have to convert the NSArray
to a plain C array. 我想你必须将
NSArray
转换为普通的C数组。 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 NSNumber
s): 或者,作为评论者的建议(假设您的
NSArray
包含NSNumber
):
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];
}
Check out the answer that mentions using [NSArray getObjects] to create a c-style array. 查看使用[NSArray getObjects]创建c样式数组的答案。
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);
Alternately, since CFArray is toll-free bridged to NSArray, could you call those C functions from your C++ function? 或者,由于CFArray是免费桥接到NSArray,你能从C ++函数调用那些C函数吗? 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.
我环顾四周,如果没有C ++包装器来提供类似的语义,或者可以轻松编写一个,那就不会感到惊讶。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.