简体   繁体   English

从Objective-C函数返回2D C数组

[英]Returning a 2D C array from an Objective-C function

I want to do achieve something like this in Objective-C 我想在Objective-C中实现类似的功能

+(int[10][10])returnArray
{
    int array[10][10];
    return array;
}

However, this gives an "array initializer must be an initializer list" compiler error. 但是,这给出了“数组初始值设定项必须是初始化列表”编译器错误。 Is this at all possible? 这是可能吗?

You can't return an array (of any dimension) in C or in Objective-C. 您无法在C或Objective-C中返回数组(任何维度)。 Since arrays aren't lvalues, you wouldn't be able to assign the return value to a variable, so there's no meaningful for such a thing to happen. 由于数组不是左值,因此您无法将返回值赋给变量,因此对于这样的事情没有意义。 You can work around it, however. 但是,你可以解决它。 You'll need to return a pointer, or pull a trick like putting your array in a structure: 你需要返回一个指针,或者像把数组放在一个结构中一样窍门:

// return a pointer
+(int (*)[10][10])returnArray
{
    int (*array)[10][10] = malloc(10 * 10 * sizeof(int));
    return array;
}

// return a structure
struct array {
  int array[10][10];
};

+(struct array)returnArray
{
   struct array array;
   return array;
}

Another way you can do it with objective C++, is to declare the array as follows: 使用目标C ++可以实现的另一种方法是按如下方式声明数组:

@interface Hills : NSObject
{


@public
    CGPoint hillVertices[kMaxHillVertices];
}

This means the array is owned by the Hills class instance - ie it will go away when that class does. 这意味着该数组由Hills类实例拥有 - 也就是说,当该类实例时它将消失。 You can then access from another class as follows: 然后,您可以从另一个类访问如下:

_hills->hillVertices 

I prefer the techniques Carl Norum describes, but wanted to present this as an option that might be useful in some cases - for example to pass data into OpenGL from a builder class. 我更喜欢Carl Norum描述的技术,但是想要将其作为一种在某些情况下可能有用的选项 - 例如将数据从构建器类传递到OpenGL中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM