How to use variant arrays in Delphi

后端 未结 2 1474
失恋的感觉
失恋的感觉 2020-12-16 12:51

I have two Delphi7 programs: a COM automation server (EXE) and the other program which is using the automation server.

I need to pass an array of bytes from one prog

相关标签:
2条回答
  • 2020-12-16 13:30

    You create it like that:

    Declarations first

    var
      VarArray: Variant;
      Value: Variant;
    

    Then the creation:

    VarArray := VarArrayCreate([0, Length - 1], varVariant);
    

    or you could also have

    VarArray := VarArrayCreate([0, Length - 1], varInteger);
    

    Depends on the type of the data. Then you iterate like this:

    i := VarArrayLowBound(VarArray, 1);
    HighBound := VarArrayHighBound(VarArray, 1);
    
    while i <= HighBound do
    begin
      Value := VarArray[i];
      ... do something ...
      Inc(i);
    end;
    

    Finally you clear the array when you don't need it anymore. EDIT: (This is optional, see In Delphi 2009 do I need to free variant arrays? )

    VarClear(VarArray);
    

    That is all there is to it. For another example look at the official Embracadero Help

    EDIT:

    The array should be created only once. Then just use it like shown in the above example.

    0 讨论(0)
  • 2020-12-16 13:37

    For the other side:

    (assuming Value is the Variant parameter and the element type is WideString)

    var
      Source: PWideStringArray;
    
    if VarIsArray(Value) then begin
      Source:= VarArrayLock(Value);
      try
        for i:= 0 to TVarData(Value).VArray^.Bounds[0].ElementCount - 1 do
          DoWhatEverYouWantWith(Source^[i]);
        end;
      finally
        VarArrayUnlock(Value);
      end;
    end;  
    
    0 讨论(0)
提交回复
热议问题