开发者

DLLImport c++ function with default parameters

I am trying to import a function from an unmanag开发者_StackOverflow社区ed 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 default 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);


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);
}


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜