c# - 在互操作方法中为 `null` 参数传递 `ref struct` 引用

标签 c# null interop parameter-passing value-type

我正在使用 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 .

最佳答案

你有两个选择:

  1. 使somestruct成为一个类,并将函数签名更改为:

    [DllImport("MyDLL.dll", SetLastError = true)]
    public static extern uint GetValue(
        pHandle handle, somestruct a, somestruct b);
    

    通常这不能更改任何其他内容,除了您可以传递一个 null 作为 ab 的值。

  2. 为函数添加另一个重载,如下所示:

    [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/

相关文章:

c++ - 指向空对象的引用

c# - 使用来自非托管代码的托管 COM 对象

c# - 将 C++ 结构数组编码为 C#

C# 代码没有调用它应该调用的 c++ dll 函数(它有一个类指针作为参数),我不应该更改 c++ 代码

c# - iOS-Unicode取消签名

c# - 基类型的基类型

c# - 为什么 "null"出现在 C# 和 Java 中?

c# - AngularJs 和 ASP.NET MVC 5 - ng-model 覆盖文本框值

c# - 从 C# 窗体启动 VB 窗体

c++ - 空指针常量转换为纯右值