tags:

views:

33

answers:

2

I am trying to import a function from an unmanaged code c++ dll into my c# application. The c++ prototype is

int somefunction (int param1, int *param2 = NULL);

How do I declare this in c# to take advantage of the optional nature of param2? The following code does not work. param2 gets initialized with garbage.

DllImportAttribute("mydll.dll", EntryPoint = "somefunction")]
public static extern int somefunction(int param1);
A: 

Try

[DllImport("mydll.dll", EntryPoint = "somefunction")]
static unsafe extern int somefunction(int param1, int* param2 = null);

or

[DllImport("mydll.dll", EntryPoint = "somefunction")]
static extern int somefunction(int param1, IntPtr param2 = default(IntPtr));
dtb
Thanks but neither of those options will compile.
They compile fine here, but I can't test if they actually work, because I don't have your unmanaged dll.
dtb
+1  A: 

If you are using C# 4.0 then dtb`s answer is the right approach. C# 4.0 added optional parameter support and they work just as well with PInvoke functions.

Prior to C# 4.0 there is no way to take advantage of the optional parameter. The closest equivalent is to define one function that forwards into the other.

[DllImport("mydll.dll", EntryPoint = "somefunction")] 
static extern int somefunction(int param1, IntPtr param2);

static int somefunction(int param1) {
  someFunction(param1, IntPtr.Zero);
}
JaredPar