[英]DLLImport c++ function with default parameters
I am trying to import a function from an unmanaged code c++ dll into my c# application. 我正在尝试将来自非托管代码c ++ dll的函数导入到我的C#应用程序中。 The c++ prototype is
C ++原型是
int somefunction (int param1, int *param2 = NULL);
How do I declare this in c# to take advantage of the default nature of param2? 如何在c#中声明此参数以利用param2的默认性质? The following code does not work.
以下代码不起作用。 param2 gets initialized with garbage.
param2被垃圾初始化。
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,那么dtb的答案是正确的方法。 C# 4.0 added optional parameter support and they work just as well with PInvoke functions.
C#4.0添加了对可选参数的支持,它们与PInvoke函数同样有效。
Prior to C# 4.0 there is no way to take advantage of the optional parameter. 在C#4.0之前,无法利用可选参数。 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.