Introduction
Many C# programmers are familiar with the Platform Invoke mechanism (using the DllImport attribute) for calling unmanaged functions from C#.
A problem that sometimes arises is calling a function that takes a variable number of arguments. Consider, for example, the sscanf() function in the C runtime library, which is defined as follows.
This function reads data from "str," splits it up using "format," and then stores the results in the locations pointed to by the remaining arguments (the "..."), which are variable in both number and type.
So, how can we call this function from C#?
First attempt
You may be thinking, no problem, C# can cope with a variable number of arguments using its "params" keyword, which leads you to try the following code.
This builds fine, but then, when you try to run it, it blows up with a dreaded "System.AccessviolationException". So, what's wrong here?
Second attempt
The problem is that having consulted the "format" string, the C function is expected to be presented with 5-pointers in sequence. Instead, it gets a single pointer to an object array, a different animal.
This suggests that the following might work.
And indeed, it does, reconstituting the original string.
1 + 2 = three
Suppose, though, that we have a dozen such strings to process, each with different formats and different types and numbers of variables. Does this mean that we have to write out a dozen overloads of the sscanf() function to use it from C#?
The third (and final) attempt
Fortunately, we can do this with just a single function declaration by making use of the obscure (and undocumented) C# keyword __arglist. Here's how.
This gives us the same result as before, plus an extra line.
one + 2 = 3
proving that only a single function declaration is needed. So the problem is solved.