Q:

Delphi - Array of Word and PAnsichar

HI,
I using a compression delphi library that receives a pAnsiChar as parameter. But i want to store a word array in the compressed file. The prototype function is:
MyArray: TWordDynArray;
function lzopas_compress(in_p: PAnsiChar; in_len: integer; out_p: PAnsiChar): integer;

And i want to pass MyArray to the function. How do I do that?
Thanks

A:

The obvious way to accomplish this would be with a pointer cast.  The input "string" would be PAnsiChar(@MyArray[0]), and pass Length(MyArray) * sizeof(word) as the length parameter.  But this is one of those times when the obvious solution is wrong.  It may work, but since TWordDynArray is defined as an array of word and not a packed array of word, element packing issues could throw off the length calculation, and it could vary between Delphi versions.  Also, this will raise a bounds check error if Length(MyArray) = 0.
A safer way would be to create an AnsiString, set its length to Length(MyArray) * sizeof(word), and then use a loop like this:
for i := 0 to high(MyArray) do
  Move(MyArray[i], MyString[(i * sizeof(word)) + 1], sizeof(word));

And then pass your string, cast to a PAnsiChar, and the Length() of your string.

