Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PtrToStructure() generates SafeArrayTypeMismatchException

Folks,

Please help me chase out a SafeArrayTypeMismatchException that I'm getting. I need to pass a struct to unmanaged DLL. One of the struct members is a variable-length array. Unmanaged code will populate it with data, then my C# code will use the data.

My approach is this:

  1. Get IntPtr for my structure using StructureToPtr(), do the memory allocation too, of course.
  2. Call unmanaged function, and pass IntPtr as a parameter
  3. Get the populated structure using PtrToStructure()

If for the purposes of an exercise I call StructureToPtr() and PtrToStructure() back-to-back there are no exceptions.

PtrToStructure() generates SafeArrayTypeMismatchException, if I put a call to unmanaged DLL between StructureToPtr() and PtrToStructure(). The description for SafeArrayTypeMismatchException is "Mismatch has occurred between the runtime type of the array and the sub type recorded in the metadata."

Any suggestion or insight is really appreciated!

I can post my code if needed.


- Nick

like image 974
Nick Alexeev Avatar asked Jun 05 '26 18:06

Nick Alexeev


1 Answers

The .NET marshaller can't handle C/C++ arrays of unknown size. An array in .NET always has a fixed size associated with it but C/C++ arrays are just a pointer to a memory block. The marshaller has no way to know how large the array returning from the C/C++ code is, so it throws an exception.

What it's is trying to do in your case is to marshal the array as a SafeArray which is a COM type - an array that contains it's own size, but you're array isn't a SafeArray.

There isn't a way to get the marshaller to handle this automatically. Declare the struct member you are using as an IntPtr and manually create .NET array and copy the values in. See this for an example of how to do that.

like image 86
shf301 Avatar answered Jun 07 '26 16:06

shf301



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!