如何将可变数量的参数传递给可变参数函数 [英] How to pass variable number of args to a variadic function
问题描述
我有一个带有签名的可变参数函数:
I have a variadic function with the signature:
- (id)initWithNumVertices:(NSUInteger)inCount, ...;
但我不知道如何根据变量数量的顶点构造省略号部分.这怎么办?
But I cannot figure out how to construct the ellipsis part from a variable number of vertices. How can this be done?
抱歉,我不是在寻求一种编写此函数的方法,而是寻求一种使用未知 数量的变量来调用它的方法.该函数采用结构而不是对象.
sorry I wasn't asking for a way to write this function, I'm asking for a way to call it, using an unknown number of variables. The function takes structs and not objects.
如果参数的数量是已知的,我可以这样做:
If the number of arguments is known, I can do this:
[[MyObject alloc] initWithNumVertices:4, v[0], v[1], v[2], v[3]];
但是当顶点数未知时我怎么称呼它?
But how can I call this when the number of vertices is unknown?
推荐答案
如果在编译时不知道参数的数量,我认为不可能调用可变参数函数.如果您想避免使用 NSArray
的开销,将多个 C 结构传递给方法的标准方法是使用标准 C 数组.
I don't think it's possible to call a variadic function if the number of arguments is not known at compile time. If you want to avoid the overhead of using an NSArray
, the standard way of passing multiple C structs to a method would be using standard C arrays.
- (id)initWithVertices:(Vertex *)vertices count:(NSUInteger)count;
NSIndexPath
的 -indexPathWithIndexes:length:
是一个也使用这种模式的例子,还有很多其他的,它在 Cocoa 中相当常见.
NSIndexPath
's -indexPathWithIndexes:length:
is an example where this pattern is also used, there are various others, it's fairly common in Cocoa.
这篇关于如何将可变数量的参数传递给可变参数函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!