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:
IntPtr for my structure using StructureToPtr(), do the memory allocation too, of course.IntPtr as a parameterPtrToStructure()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
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.
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