Ref param returning array of unknown size. How to

2019-07-07 07:09发布

A COM component exposes an API which expects a ref param of object type. As per the documentation of this API, it will fill the ref object with array of values. Now my problem is in prod env I can't predict the number of elements which I will get back.

Following code will work.

     COMClass objCOM = new COMClass ();
     object colOfInts= new int[10]; // What if I don't know the following will return array of size 10?
     int errorcode = objCOM.FillThisIn(ref colOfInts);

But what if I don't know the size of array that API returns in ref.

Update here

        object colOfInts = null;
        int errorcode = objCOM .FillThisIn(ref colOfInts);

now when I check the type I get System.Int32[*]

Basically I need to iterate through this array and check for the presence of an element

3条回答
Emotional °昔
2楼-- · 2019-07-07 07:27

You are getting back an array whose lower bound isn't 0. That's not uncommon in COM interop, the next likely choice is 1. You don't have to copy it, you can access the elements with Array.GetValue(). Array.GetLowerBound() tells you where to start, Array.GetLength() or Array.GetUpperBound() tells you how far to go.

查看更多
走好不送
3楼-- · 2019-07-07 07:38

If you're getting back an array of System.Int32, you probably just need to cast:

    object colOfInts = null; 
    int errorcode = objCOM .FillThisIn(ref colOfInts); 

    int[] arrayOfInts = (int[]) colOfInts;

Then arrayOfInts.Length will have the number of elements in the array.

查看更多
别忘想泡老子
4楼-- · 2019-07-07 07:47

Finally I got some solution on this . Forgot to mention erroCode will have the size of the array.

        int[] test = new int[errorCode];            
        Buffer.BlockCopy((System.Array)colOfInts, 0, test, 0, errorCode * sizeof(int));
查看更多
登录 后发表回答