Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper PInvoke signature for a function that takes var args?

There is a native function:

int sqlite3_config(int, ...);

I would like to PInvoke to this function. Currently, I have this declaration:

[DllImport("sqlite3", EntryPoint = "sqlite3_config")]
public static extern Result Config (ConfigOption option);

(Result and ConfigOption are enums of the form enum Result : int { ... }.)

I am actually only interested in the single parameter version of this function and don't need the other args. Is this correct?

I am also curious as to how you would declare the two argument form (perhaps it would take 2 IntPtrs?).

like image 617
Frank Krueger Avatar asked Jan 23 '10 19:01

Frank Krueger


1 Answers

You need to use the __arglist keyword (which is undocumented), Bart# had a nice blog about it.

Example

class Program
{
    [DllImport("user32.dll")]
    static extern int wsprintf([Out] StringBuilder lpOut, string lpFmt, __arglist);

    static void Main(String[] args)
    {
        var sb  = new StringBuilder();
        wsprintf(sb, "%s %s %s", __arglist("1", "2", "3"));
        Console.Write(sb.ToString());
    }       
}

The is no standard way of pinvoking vararg methods, most solutions will wrap it in several methods e.g.

[DllImport("MyDll", CallingConvention=CallingConvention.Cdecl)]
static extern var MyVarArgMethods1(String fmt, 
    String arg1);

[DllImport("MyDll", CallingConvention=CallingConvention.Cdecl)]
static extern var MyVarArgMethods2(String fmt, 
    String arg1, String arg2);
like image 197
Shay Erlichmen Avatar answered Sep 28 '22 07:09

Shay Erlichmen