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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With