我正在使用 C# 调用 DLL 函数。
[DllImport("MyDLL.dll", SetLastError = true)]
public static extern uint GetValue(
pHandle handle,
ref somestruct a,
ref somestruct b);
我怎样才能传递 null
参数 3 的引用?
当我尝试时,出现编译时错误:
Cannot convert from
<null>
to ref somestruct.
我也试过IntPtr.Zero
.
最佳答案
你有两个选择:
使
somestruct
成为一个类,并将函数签名更改为:[DllImport("MyDLL.dll", SetLastError = true)] public static extern uint GetValue( pHandle handle, somestruct a, somestruct b);
通常这不能更改任何其他内容,除了您可以传递一个
null
作为a
和b
的值。为函数添加另一个重载,如下所示:
[DllImport("MyDLL.dll", SetLastError = true)] public static extern uint GetValue( pHandle handle, IntPtr a, IntPtr b);
现在您可以使用
IntPtr.Zero
调用该函数,此外还可以使用ref
来调用somestruct
类型的对象:GetValue(myHandle, ref myStruct1, ref myStruct2); GetValue(myHandle, IntPtr.Zero, IntPtr.Zero);
关于c# - 在互操作方法中为 `null` 参数传递 `ref struct` 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15217406/