C#:如何将 null 传递给需要 ref 的函数? [英] C#: How to pass null to a function expecting a ref?
问题描述
我有以下功能:
public static extern uint FILES_GetMemoryMapping(
[MarshalAs(UnmanagedType.LPStr)] string pPathFile,
out ushort Size,
[MarshalAs(UnmanagedType.LPStr)] string MapName,
out ushort PacketSize,
ref Mapping oMapping,
out byte PagesPerSector);
我想这样称呼:
FILES_GetMemoryMapping(MapFile, out size, MapName,
out PacketSize, null, out PagePerSector);
不幸的是,我无法在需要类型 ref Mapping
的字段中传递 null
并且我尝试过的任何强制转换都无法解决此问题.
Unfortunately, I cannot pass null
in a field that requires type ref Mapping
and no cast I've tried fixes this.
有什么建议吗?
推荐答案
我假设 Mapping 是一种结构?如果是这样,您可以拥有具有不同签名的两个版本的 FILES_GetMemoryMapping()
原型.对于要传递 null
的第二个重载,将参数设为 IntPtr
并使用 IntPtr.Zero
I'm assuming that Mapping is a structure? If so you can have two versions of the FILES_GetMemoryMapping()
prototype with different signatures. For the second overload where you want to pass null
, make the parameter an IntPtr
and use IntPtr.Zero
public static extern uint FILES_GetMemoryMapping(
[MarshalAs(UnmanagedType.LPStr)] string pPathFile,
out ushort Size,
[MarshalAs(UnmanagedType.LPStr)] string MapName,
out ushort PacketSize,
IntPtr oMapping,
out byte PagesPerSector);
调用示例:
FILES_GetMemoryMapping(MapFile, out size, MapName,
out PacketSize, IntPtr.Zero, out PagePerSector);
如果 Mapping 实际上是一个类而不是一个结构,只需在传递之前将值设置为 null.
If Mapping is actually a class instead of a structure, just set the value to null before passing it down.
这篇关于C#:如何将 null 传递给需要 ref 的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!