开发者

What is this `Object[*]` type I get with 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-dimensio开发者_开发技巧nal 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 );


This was such a PITA. I had this code in two projects:

Workbook wb = null;
try
{
    wb = excel.Workbooks.Open(filePath, false, true, 5, null, "WrongPAssword");
}
catch
{
    return false;
}    

try
{

    Array links = (Array)wb.LinkSources(XlLink.xlExcelLinks);
    if (links != null)
    {

One worked the other did not. The Difference. Working one was targeting .Net 2.0 and other one was .Net 4.0 that was giving the error:

Unable to cast object of type 'System.Object[*]' to type 'System.Object[]'.

Turns out if you change the Visual Studio version of this article from VS2005 to VS2010 the LinkSources datatype changes.

MSDN Workbook.LinkSources Method

VS2010:

Object LinkSources(
    Object Type
)

VS2005:

public virtual Object LinkSources (
    [OptionalAttribute] Object Type
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜