gpt4 book ai didi

cocoa - NSArray 到 C 数组

转载 作者:行者123 更新时间:2023-12-03 16:02:06 24 4
gpt4 key购买 nike

我们可以将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com