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

可紊 提交于 2019-12-05 06:55:38
Shay Erlichmen

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