Hello,
like the Topic says: what is the Difference between:
@
and
Pointer ?
I was thinking that @ is the same as Pointer - only as short Form ...
I have the follow Code (which produce Error):
Error: Can't assign values to an address
function Foo: String;
begin
...
GetMem(@result, len + 1);
...
end;
Then I had replace @ with Pointer, and all will done okay:
function Foo: String;
begin
...
GetMem(Pointer(result), len + 1);
...
end;
Your code is wrong in any way you spin it no matter whether the compiler compiles it or not.
First of,
GetMem expects a value to assigned to as its first parameter. You
can't change the value of an
@-expression however. And using the cast either results in the first 4 or 8 Byte of the result variable to contain garbage (namely the address of the allocated memory) in case
String is
ShortString or to point to invalid string data in case
String is
AnsiString or
UnicodeString, cause these managed types consist of more than “
len + 1”.
So if you want to do this in a right way, either don't allocate anything at all if
String is
ShortString cause it will be passed as a whole 256 Byte
anyway or use the variant of
GetMem that takes a single parameter (the size) and returns the pointer and cast that to
String and more importantly allocate
len + SizeOf(TAnsiRec) or
len + SizeOf(TUnicodeRec) depending on whether
String is
AnsiString or
UnicodeString respectively.
More importantly I'd suggest you to simply let the RTL do its thing instead of trying to outsmart it.