This is called the variational function. The P / Invoke support information is pretty scarce for them, that's what I found out.
I could not find a way to direct DllImportfunction with a variable number of arguments. I had DllImportall the options for arguments as different overloads.
Take wsprintf for example . It has the following prototype in winuser.h:
int WINAPIV wsprintf(
LPTSTR lpOut,
LPCTSTR lpFmt,
...);
# :
using System;
using System.Text;
using System.Runtime.InteropServices;
class C {
[DllImport("user32.dll", CallingConvention=CallingConvention.Cdecl)]
static extern int wsprintf(
[Out] StringBuilder buffer,
string format,
int arg);
[DllImport("user32.dll", CallingConvention=CallingConvention.Cdecl)]
static extern int wsprintf(
[Out] StringBuilder buffer,
string format,
int arg1,
string arg2);
public static void Main() {
StringBuilder buffer = new StringBuilder();
int result = wsprintf(buffer, "%d + %s", 42, "eggs!");
Console.WriteLine("result: {0}\n{1}", result, buffer);
}
}
complexFunction.
char* complexFunction(char* arg1, ...);
varargs : . - . , complexFunction char. , , . , , void free(void*).
, , # complexFunction :
using System;
using System.Text;
using System.Runtime.InteropServices;
class C {
[DllImport("your.dll",
CallingConvention=CallingConvention.Cdecl,
CharSet=CharSet.Ansi)]
static extern IntPtr complexFunction(
string format,
int arg1, int arg2);
[DllImport("your.dll", CallingConvention=CallingConvention.Cdecl)]
static extern void free(IntPtr p);
public static void Main() {
IntPtr pResult = complexFunction("%d > %s", 2, 1);
string sResult = Marshal.PtrToStringAnsi(pResult);
free(pResult);
Console.WriteLine("result: {0}", sResult);
}
}