I do C# excel interop. I call macros from C#, and I expect arrays of objects. I'm able to get 2-dimensional arrays of objects from the macros which returns 2-dimensional arrays.
However, an other (third party) macro is supposed to return a one-dimensional array. I can't get the (object[])xlApp.Run(...)
working (it throws an exception), and the type info in the debugger says the result is of type Object[*]
. The actual message from the exception is
Unable to cast object of type 'System.Object[*]' to type 'System.Object[]'.
What is this Object[*]
type and how do I retrieve a one-dimensional array from this ?
EDIT: It occurred to me that this could mean a SAFEARRAY of VARIANTS. But then, two questions arise: why is everything ok with 2-dimensional arrays ? How do I convert a SAFEARRAY to a C# array ?
I foulnd various articles about your problem :
OPCFondation : Basically instead of declaring it as an array of objects, you can just declare it as an Array without providing any element type. So do not cast in Object[] but Array, and use a foreach loop to use the subarray.
foreach(object subobject in (Array)myarrayitem)
{
//do stuff with the subobject, even browse further
}
This solution seems to work since you can find it again here.
On StackOverflow : they speak about arrays with lower bound > 0, which gives you the Object[*] type, with some links that can be interesting about the subject, but I think the first idea is the good one.
Use
System.Array a = (System.Array)((object) returnedObject );
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