Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When passing null to Interop method it throws "Generic types cannot be marshaled." exception

I'm working with a C++ dll that is imported like this:

    [DllImport("Bank.dll"]
    static extern int GetDevice(byte versionCode, byte deviceAddress);

I can successfully access this method with not null arguments like this:

    GetDevice(0, 3);

But calling this method with null arguments like this:

    [DllImport("Bank.dll"]
    static extern int GetDevice(byte versionCode, Nullable<byte> deviceAddress);
    GetDevice(0, null);

Gives the following runtime error:

An unhandled exception of type 'System.Runtime.InteropServices.MarshalDirectiveException' occurred. Additional information: Cannot marshal 'parameter #2': Generic types cannot be marshaled.

How do I successfully pass null arguments to this method?

like image 842
Bosah Chude Avatar asked Sep 30 '22 06:09

Bosah Chude


1 Answers

I am guessing that you have mistaken Nullable<byte> as being equivalent to C++'s unsigned char * or similar. It's not. It is literally a single byte, but where the value can also be null.

As the error message says, you also are not permitted to pass generic types, and of course Nullable<T> is a generic type. So even if it semantically meant what you wanted, it wouldn't be allowed.

But per your question, "How do I successfully pass null arguments to this method?", that suggests that what you are really dealing with is a pointer type as the parameter type. Without a complete code example it's impossible to know for sure what your declaration and usage should be. But it's likely you can just declare the parameters as a byte[], and p/invoke will marshal it correctly, including mapping a managed null reference to a null pointer.

I.e. just declare your method like this:

[DllImport("Bank.dll"]
static extern int GetDevice(byte versionCode, byte[] deviceAddress);

The default marshaling should work for you. If not, then you'll need to edit your question to include the exact C++ declaration you're trying to call.

like image 156
Peter Duniho Avatar answered Oct 06 '22 19:10

Peter Duniho