Search code examples
c#nullinteropparameter-passingvalue-type

Passing `null` reference for a `ref struct` parameter in interop method


I am using C# to call a DLL function.

[DllImport("MyDLL.dll", SetLastError = true)]
public static extern uint GetValue(
        pHandle handle,
        ref somestruct a,
        ref somestruct b);

How can I pass a null reference for argument 3?

When I try, I am getting a compile-time error:

Cannot convert from <null> to ref somestruct.

I also tried IntPtr.Zero.


Solution

  • You have two options:

    1. Make somestruct a class, and change the function signature to:

      [DllImport("MyDLL.dll", SetLastError = true)]
      public static extern uint GetValue(
          pHandle handle, somestruct a, somestruct b);
      

      Usually this must not change anything else, except that you can pass a null as the value of a and b.

    2. Add another overload for the function, like this:

      [DllImport("MyDLL.dll", SetLastError = true)]
      public static extern uint GetValue(
          pHandle handle, IntPtr a, IntPtr b);
      

      Now you can call the function with IntPtr.Zero, in addition to a ref to an object of type somestruct:

      GetValue(myHandle, ref myStruct1, ref myStruct2);
      GetValue(myHandle, IntPtr.Zero, IntPtr.Zero);