Search code examples
delphicomdelphi-2010safearray

Two dimensional Safearray in delphi?


I need to Unittest a COM method therefor i need to create a two dimensional Safearray of type string.

How to do that?


Solution

  • Create a two dimensional array like this:

    var
      arr: Variant;
    ....
    arr := VarArrayCreate([1, 10, 1, 5], varInteger);
    

    This creates an array whose primary dimension has bounds 1..10 and whose secondary dimension has bounds 1..5:

          1      2      3      4      5 
      ┌──────┬──────┬──────┬──────┬──────┐
     1│ [1,1]│ [1,2]│ [1,3]| [1,4]| [1,5]│
      ├──────┼──────┼──────┼──────┼──────┤
     2│ [2,1]│ [2,2]│ [2,3]| [2,4]| [2,5]│
      ├──────┼──────┼──────┼──────┼──────┤
     3│ [3,1]│ [3,2]│ [3,3]| [3,4]| [3,5]│
      ├──────┼──────┼──────┼──────┼──────┤
     4│ [4,1]│ [4,2]│ [4,3]| [4,4]| [4,5]│
      ├──────┼──────┼──────┼──────┼──────┤
     5│ [5,1]│ [5,2]│ [5,3]| [5,4]| [5,5]│
      ├──────┼──────┼──────┼──────┼──────┤
     6│ [6,1]│ [6,2]│ [6,3]| [6,4]| [6,5]│
      ├──────┼──────┼──────┼──────┼──────┤
     7│ [7,1]│ [7,2]│ [7,3]| [7,4]| [7,5]│
      ├──────┼──────┼──────┼──────┼──────┤
     8│ [8,1]│ [8,2]│ [8,3]| [8,4]| [8,5]│
      ├──────┼──────┼──────┼──────┼──────┤
     9│ [9,1]│ [9,2]│ [9,3]| [9,4]| [9,5]│
      ├──────┼──────┼──────┼──────┼──────┤
    10│[10,1]│[10,2]│[10,3]|[10,4]|[10,5]│
      └──────┴──────┴──────┴──────┴──────┘
    

    When you say that you want to create an array that contains strings, I presume you are referring to the COM BSTR. In which case pass varOleStr as the var type parameter when you call VarArrayCreate.