How to pass variable number of args to a variadic function

情到浓时终转凉″ 提交于 2019-12-13 14:43:11

问题


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?

EDIT: 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?


回答1:


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's -indexPathWithIndexes:length: is an example where this pattern is also used, there are various others, it's fairly common in Cocoa.




回答2:


Edit: Just use a native C array. A variadic method won't help you here.


In your case, since you have an unspecified number of arguments, you'd have to rewrite it in this form:

- (id)initWithVertices:(vertex)firstVertex;

which runs a while loop until it hits a vertex specified as illegal (that will be your break point), sort of like this:

vertex currentVertex, invalidVertex = // some invalid value, like {-1, -1}
while ((currentVertex = va_arg(args, vertex) != invalidVertex) {
    // initialization code with the current vertex
    // when we hit 'invalidVertex', which will be at the end of the list, stop
}  

Code like that has to be run like this:

[[MyObject alloc] initWithVertices:firstVertex, secondVertex, thirdVertex, nullVertex];

nullVertex has to be at the end of the list in order to specify the last of the valid vertices (much like NSArray's arrayWithObjects: method has to have nil at the end of the list).




回答3:


Are you asking how to separate the arguments?

[[YourObject alloc] initWithNumVertices:7, 8, 9, 10];

EDIT | Oh, I think I see what you're asking. You want to invoke this method dynamically, such as with objc_msgSend() or via NSInvocation? Disregard my answer if that's the case.




回答4:


If you haven't already, look at libffi (`man ffi'):

DESCRIPTION The foreign function interface provides a mechanism by which a function can generate a call to another function at runtime without requiring knowledge of the called function's interface at compile time.

You should be able to invoke objc_msgSend() using this if I understand correctly.



来源:https://stackoverflow.com/questions/4703877/how-to-pass-variable-number-of-args-to-a-variadic-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!