Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 536
user1964059 Avatar asked Mar 05 '13 06:03

user1964059


People also ask

Can a ref be null?

A React ref most commonly returns undefined or null when we try to access its current property before its corresponding DOM element is rendered. To get around this, access the ref in the useEffect hook or when an event is triggered.

Can you pass null as argument C#?

Yes. There are two kinds of types in . NET: reference types and value types. References types (generally classes) are always referred to by references, so they support null without any extra work.

How do you pass reference parameters in C#?

Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference with the intent of changing the value, use the ref , or out keyword.

What is ref parameter in C#?

When used in a method's parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The ref keyword makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument.


1 Answers

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);
    
like image 58
Mohammad Dehghan Avatar answered Sep 20 '22 14:09

Mohammad Dehghan