[Lazarus] Use of Move()?

Marc Weustink marc at dommelstein.net
Wed Feb 2 00:00:35 CET 2011


On 1-2-2011 23:51, Bo Berglund wrote:
> On Tue, 01 Feb 2011 23:33:58 +0100, Marc Weustink
> <marc at dommelstein.net>  wrote:
>
>>
>> Just tested:
>>
>> program MoveTest;
>> {$mode objfpc}{$H+}
>> uses
>>    SysUtils;
>> var
>>    S: String;
>>    I: Integer;
>>    P: Pointer;
>> begin
>>    S := 'Bla';
>>    S := S + S;
>>    P := @I;
>>    Move(S[1], P^, SizeOf(I));
>>
>>    WriteLn(Format('%x %x %x %x %8.8x', [Ord(S[1]), Ord(S[2]), Ord(S[3]),
>> Ord(S[4]), i]));
>> end.
>>
>> $ ./movetest
>> 42 6C 61 42 42616C42
>>
>
> My code is a bit more complex because I want to be able to read and
> write different types of variables to the buffer handler.
> As an example I have the case of a string variable. To write it into
> the buffer I use this overloaded write:
>
> function TSSCommBuf.Write(const Source: string): boolean;
> begin
>    Result := Write(@Source[1], Length(Source));
> end;
>
> and for a Cardinal argument I use this:
>
> function TSSCommBuf.Write(const Source: Cardinal): boolean;
> begin
>    Result := Write(@Source, SizeOf(Source));
> end;
>
> both of which then calls the main Write:
>
> function TSSCommBuf.Write(Source: Pointer; Count: Cardinal): boolean;
> var
>    b: byte; //For debugging, will be removed later
>    Dst: Pointer; //Suggestion from Marc Weustink
> begin
>    Result := false;
>    //Check buffer size and grow if needed
>    if (FBufSize - FWriteIndex)<  Count then
>      ExpandBuffer(FWriteIndex - FBufSize + Count);
>    Dst := @FBuf[FWriteIndex];
>    Move(Source, Dst^, Count); // Source and Dst are pointers
>    b := FBuf[FWriteIndex]; //To check what actually was written
>    FWriteIndex := FWriteIndex + Count;
>    Result := true;
> end;
>
> When I call the Write method with a string argument I get first to the
> small overloaded function, which unifies the arguments and calls the
> main Write.
>
> But when I test this with the string containing the single char #6
> then the value that actually gets written is #64....
>
> So somehow I am missing something important here...

Move expects 2 untyped parameters, so dereference your pointers

   Move(Source^, Dst^, Count); // Source and Dst are pointers

Marc




More information about the Lazarus mailing list