cocoa - NSArray 到 C 数组

标签 cocoa opengl

我们可以将 NSArray 转换为 C 数组吗?

如果没有,还有什么替代方案吗?假设我需要将 C 数组提供给 OpenGL 函数,其中 C 数组包含从 plist 文件读取的顶点指针。

最佳答案

答案取决于 C 数组的性质。

如果您需要填充原始值且长度已知的数组,您可以执行以下操作:

NSArray* nsArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
                                             [NSNumber numberWithInt:2],
                                             nil];
int cArray[2];

// Fill C-array with ints
int count = [nsArray count];

for (int i = 0; i < count; ++i) {
    cArray[i] = [[nsArray objectAtIndex:i] intValue];
}

// Do stuff with the C-array
NSLog(@"%d %d", cArray[0], cArray[1]);

下面是一个示例,我们希望从 NSArray 创建一个新的 C 数组,并将数组项保留为 Obj-C 对象:

NSArray* nsArray = [NSArray arrayWithObjects:@"First", @"Second", nil];

// Make a C-array
int count = [nsArray count];
NSString** cArray = malloc(sizeof(NSString*) * count);

for (int i = 0; i < count; ++i) {
    cArray[i] = [nsArray objectAtIndex:i];
    [cArray[i] retain];    // C-arrays don't automatically retain contents
}

// Do stuff with the C-array
for (int i = 0; i < count; ++i) {
    NSLog(cArray[i]);
}

// Free the C-array's memory
for (int i = 0; i < count; ++i) {
    [cArray[i] release];
}
free(cArray);

或者,您可能希望以 nil 终止数组,而不是传递其长度:

// Make a nil-terminated C-array
int count = [nsArray count];
NSString** cArray = malloc(sizeof(NSString*) * (count + 1));

for (int i = 0; i < count; ++i) {
    cArray[i] = [nsArray objectAtIndex:i];
    [cArray[i] retain];    // C-arrays don't automatically retain contents
}

cArray[count] = nil;

// Do stuff with the C-array
for (NSString** item = cArray; *item; ++item) {
    NSLog(*item);
}

// Free the C-array's memory
for (NSString** item = cArray; *item; ++item) {
    [*item release];
}
free(cArray);

关于cocoa - NSArray 到 C 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1011711/

相关文章:

macos - Webview loadRequest 不起作用

ios - 奇怪的构建错误,类名问题?

objective-c - NSTextView查找栏的下一个关键 View

animation - glutMainLoop() 与 glutTimerFunc()?

c++ - 内存池算法

macos - 为什么 AXUIElementCopyAttributeValue() 会为此函数中屏幕上的每个窗口返回 kAXErrorAttributeUnsupported ?

iphone - 核心数据 : Checking for Null

c++ - 将鼠标点转换为二次 B 样条

OpenGL : Suggestion on handling collision detection and vertex data?

OpenGL:深度计算不连续