如何将可为 null 的类型传递给 P/调用的函数
我有一些 p/invoked 函数(但我现在正在重写我的代码,所以我正在整理),我想知道如何使用/传递可为空类型作为参数之一。 使用 int 类型不是问题,但考虑到以下情况:
[DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid, int? enumerator, IntPtr hwndParent, uint Flags);
我希望能够将 Guid
参数作为可为 null 的类型传递。 目前我可以将其称为:
SetupDiGetClassDevs(ref tGuid, null, IntPtr.Zero, (uint)SetupDiFlags.DIGCF_PRESENT );
但我需要第一个参数也可以作为 null
传递。
I have a few p/invoked functions (but I'm rewriting my code at the moment so I'm tidying up) and I want to know how to use/pass a nullable type as one of the parameters. working with int types isn't a problem but given the following:
[DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid, int? enumerator, IntPtr hwndParent, uint Flags);
I'd like to be able to pass the Guid
parameter as a nullable type. As it stands at the moment I can call it as:
SetupDiGetClassDevs(ref tGuid, null, IntPtr.Zero, (uint)SetupDiFlags.DIGCF_PRESENT );
but I need the first parameter to also be passable as null
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有在本机代码中进行一些有趣的字节操作,则不可能将 Nullable 类型传递到 PInvoke 函数中,而这几乎肯定不是您想要的。
如果您需要能够将结构体值作为 NULL 传递给本机代码,请声明 PInvoke 声明的重载,该重载采用 IntPtr 代替结构体并传递 IntPtr.Zero
注意:我向第一个签名添加了一个 ref 类。 如果本机签名可以采用 NULL,则它很可能是指针类型。 因此,您必须通过引用传递值类型。
现在您可以拨打如下电话
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
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