How to pass a nullable type to a P/invoked function [duplicate]

懵懂的女人 提交于 2019-11-27 09:05:20

It's not possible to pass a Nullable type into a PInvoke'd function without some ... interesting byte manipulation in native code that is almost certainly not what you want.

If you need the ability to pass a struct value as NULL to native code declare an overload of your PInvoke declaration which takes an IntPtr in the place of the struct and pass 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);

Note: I added a ref class to the first signature. If the native signature can take NULL, it is likely a pointer type. Hence you must pass value types by reference.

Now you can make calls like the following

if (enumerator.HasValue) { 
  SetupDiGetClassDevs(someGuid, ref enumerator.Value, hwnd, flags);
} else {
  SetupDiGetClassDevs(someGuid, IntPtr.Zero, hwnd, flags);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!