c0D3l0g1c c0D3l0g1c - 4 months ago 17
C# Question

.NET Byte Array COM casting issue

I have a dynamic method call to a COM object. When I try returning the result as byte[], I get the following exception:


System.InvalidCastException: Unable to cast object of type 'System.Byte[*]' to type 'System.Byte[]'


Any help would be appreciated.

Answer

The COM object method in your case seems to return a non-zero lower bound array. You can create a normal byte array and then copy the data from the first array like this:

var comArray = (Array)(object)comObject.CallToComObject();

byte[] data = new byte[comArray.Length];

Array.Copy(comArray, data, data.Length);

I am not sure if there is a way to avoid copying.

EDIT:

For a reason unknown to me, if the non-zero lower bound array is returned in a dynamic way, i.e, the signature of CallToComObject has a dynamic return value type, then an exception will be thrown if we simply try to cast it as Array. Casting it to an object first seems to solve the problem. I don't know why.