I have a COM component written in C++. One of the MIDL interfaces has a function defined like:
HRESULT __stdcall GetValues(
int length,
[ref, size_is(*length)] VARIANT_BOOL out[]);
GetValues just populates the out array with values:
for (int i = 0; i < length; ++i)
out[i] = (i % 2) != 0;
I’ve tried to call it from C# using the following:
private bool[] mValues = new bool[100];
...
myComObject.GetValues(100, ref this.mValues[0]);
I’m getting access violation errors. I think the C++ is interpreting the bools as 2-byte values, whereas in C# they’re only allocated as 1-byte values.
I’ve looked at Default Marshaling for Boolean Types but I’m not sure how to apply that to my situation. The MarshalAs attribute doesn’t seem to change anything. I’m not sure how to use it for passing an array by reference?
[MarshalAs(UnmanagedType.U1)]
private bool[] mValues = new bool[100];
VARIANT_BOOLis indeed a 2-byte value: http://blogs.msdn.com/b/oldnewthing/archive/2004/12/22/329884.aspxSo when you marshal it as
UnmanagedType.VariantBool, you’re not changing anything because you’re marshalling it in as exactly the same thing that’s being returned anyway.What I would try first is
UnmanagedType.U1. If that doesn’t work, I would try to ashort[]instead ofbool[].