I wrote two methods with a void type parameter:
procedure Method1(const MyVar; size: cardinal);
var
Arr: array of byte;
begin
SetLength(Arr, size);
{now copy the data from MyVar to Arr, but how?}
end;
procedure Method2(var MyVar; size: cardinal);
var
Arr: array of byte;
begin
SetLength(Arr, size);
{return the data from the array, but how?}
end;
In the first one I would like to access the MyVar as an array of byte. In the second one, I would like to copy the data from the local array Arr to MyVar. Therefore I used the CopyMemory() function, but something is wrong with it.
If I use the following in the second method, it is fine as long as Method2 is called with an array as its parameter (Method2(Pointer(MyString)^, Length(MyString)) or Method2(Pointer(MyArray), Length(MyArray))).
CopyMemory(Pointer(MyVar), Pointer(Arr), size);
If I call Method2 with a, for instance, integer parameter (Method2(MyInteger, SizeOf(MyInteger))), it does not work properly. In this case, the CopyMemory() has to be called this way:
CopyMemory(@MyVar, Pointer(Arr), size);
How to return data from Method2 correctly not knowing whether it is a simple type (or record) or an array? The situation will be similar in Method1, but here I would have to use
CopyMemory(Pointer(Arr), Pointer(MyVar), size);
in case of arrays and
CopyMemory(Pointer(Arr), @MyVar, size);
in case of simple types.
What can I do about it when I don't know what the MyVar parameter is?
Thanks in advance.