Passing Dynamic Arrays by Reference in SmartMS

Top 

Example code : Passing Dynamic Arrays by Reference in SmartMS

// Pass by Value

procedure IncArray1(data: array of integer);

var i : integer;

begin

  for i := Low(data) to High(data) do

    data[i] := data[i] + 5;

end;

 

// Pass by Reference

procedure IncArray2(var data: array of integer);

var i : integer;

begin

  for i := Low(data) to High(data) do

    data[i] := data[i] + 5;

end;

 

procedure TForm1.W3Button4Click(Sender: TObject);

var

  data: array of integer;

begin

  data.SetLength(1); //SetLength(data, 1);

  data[0] := 37;

  IncArray1(data);

  ShowMessage( IntToStr(data[0]) );  //37

 

  IncArray2(data);

  ShowMessage(IntToStr(data[0]) );   //42

end;

Result in Delphi:

With current Delphi syntax, dynamic arrays are passed by reference, like a TObject would be, but resized as value types:

- The IncArray1 method doesn't use the prefix 'var', this treat arrays as a value type (compiler will make a copy).

- The IncArray2 method uses the keyword 'var', this treat arrays as a reference type.

So the resuilt will be: 37 and 42

Note that data[0] will be unchanged after call IncArray1 method. If you want to resize a dynamic array you have to pass it as a var parameter (like IncArray2), the array will be updated to 42.

Result in SmartMS:

In SmartMS, dynamic arrays are supported as reference types. In essence, a pure reference dynamic array 

is similar to having direct language support for something like a TList.

So the result will be: 42 and 47

Note that data[0] will be changed after call IncArray1 and IncArray2 methods. SmartMS makes SetLength() treat dynamic arrays as a reference type, ie. have it work as dynamic. You don't need to use var keyword to pass as reference.

If you need to make a unique copy of a dynamic array, you would use a dedicated function called Copy() rather than SetLength() you would do it in Delphi.