Search code examples
arraysdelphipointersdynamic-arrays

Compatibility of the tricky dynamic arrays with dynamic arrays


Considering the old trick to make an array

Type
  IntArray = Array Of Integer;
  PIntArray = ^IntArray
  PTDynIntArray = ^TDynIntArray;
  TDynIntArray = Array[0..0] Of Integer;

{later...}

GetMem(APTDynIntArray,100*SizeOf(Integer));
APTDynIntArray^[49] := 50

Is There a way to make this tricky array compatible with a standard dynamic array ?

For example, If I want to translate an old (lets say from 1999) unit with

Procedure DoSomething(Data: PTDynIntArray);

And considering that the data will be processed using the above syntax (dataname-dereference-index in brackets), Delphi compiler will not stop if I pass a PIntArray as argument, however I get an AV at run-time (I guess that Delphi considers, in this case, that PIntArray Is the same as PTDynIntArray)

So can these two types (PIntArray and PTDynIntArray) be combined, type casted, inter-changed ? How ?


Solution

  • You can convert an IntArray (note: not PIntArray) to a PTDynIntArray. The reverse is not generally possible.

    An IntArray is stored as a pointer to the first element of the array. The array is preceded by information about the array's length and such, but if your procedure only accesses the array elements, they won't do any harm.

    You may, to be explicit, also write it as @IntArray[0].