C#: How to pass null to a function expecting a ref?
Mapping oMapping = null;
FILES_GetMemoryMapping(MapFile, out size, MapName, out PacketSize, ref oMapping, out PagePerSector);
The reason you cannot pass null
is because a ref
parameter is given special treatment by the C# compiler. Any ref
parameter must be a reference that can be passed to the function you are calling. Since you want to pass null
the compiler is refusing to allow this since you are not providing a reference that the function is expecting to have.
Your only real option would be to create a local variable, set it to null
, and pass that in. The compiler will not allow you to do much more than that.
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);
Call example:
FILES_GetMemoryMapping(MapFile, out size, MapName,
out PacketSize, IntPtr.Zero, out PagePerSector);
If Mapping is actually a class instead of a structure, just set the value to null before passing it down.
One way is to create a dummy variable, assign it null, and pass that in.