如何可空类型传递给P /调用的功能[重复]如何可空类型传递给P /调用的功能[重复](How to

2019-05-12 02:18发布

这个问题已经在这里有一个答案:

  • 如何处理在C#null或可选的DLL结构参数 1回答

我有几个P /调用的函数(但我此刻的重写我的代码,所以我整理),我想知道如何使用/传递一个空类型作为参数之一。 在int型的工作是没有问题的,但考虑到以下几点:

[DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid, int? enumerator, IntPtr hwndParent, uint Flags);

我希望能够传递Guid参数为可空类型。 因为它代表的那一刻,我可以称呼其为:

SetupDiGetClassDevs(ref tGuid, null, IntPtr.Zero, (uint)SetupDiFlags.DIGCF_PRESENT );

但我需要的第一个参数也可通过为null

Answer 1:

这是不可能的可空类型传递到一个PInvoke'd功能,无需在本机代码中的一些...有趣字节操作是几乎可以肯定不是你想要的。

如果你需要传递一个结构值作为NULL为本地代码的能力,声明你PInvoke的声明的重载这需要一个IntPtr在结构中的位置,并传递IntPtr.Zero

[DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid, ref int enumerator, IntPtr hwndParent, uint Flags);
[DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid, IntPtr enumerator, IntPtr hwndParent, uint Flags);

注:我添加了一个引用类的第一个签名。 如果本地签名可以采取NULL,它可能是一个指针类型。 因此,你必须通过引用传递值类型。

现在,你可以像下面的调用

if (enumerator.HasValue) { 
  SetupDiGetClassDevs(someGuid, ref enumerator.Value, hwnd, flags);
} else {
  SetupDiGetClassDevs(someGuid, IntPtr.Zero, hwnd, flags);
}


文章来源: How to pass a nullable type to a P/invoked function [duplicate]