How to pass variable number of args to a variadic function
I have a variad开发者_高级运维ic 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?
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.
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).
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.
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.
精彩评论