Search code examples
c#nullpinvokeparametersref

C#: How to pass null to a function expecting a ref?


I've got the following function:

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);

Which I would like to call like this:

FILES_GetMemoryMapping(MapFile, out size, MapName,
    out PacketSize, null, out PagePerSector);

Unfortunately, I cannot pass null in a field that requires type ref Mapping and no cast I've tried fixes this.

Any suggestions?


Solution

  • 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.