Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this `Object[*]` type I get with COM interop?

Tags:

c#

com-interop

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 ?

like image 921
Alexandre C. Avatar asked Dec 27 '10 14:12

Alexandre C.


2 Answers

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.

like image 152
LaGrandMere Avatar answered Oct 17 '22 02:10

LaGrandMere


Use

System.Array a = (System.Array)((object)  returnedObject );
like image 40
sikalvag Avatar answered Oct 17 '22 02:10

sikalvag