天天看點

Delphi-string轉pbyte的方法——Move函數!

var

   s:string;

   ps:Pchar;

   b:pbyte;

   len:integer;

begin

   s:=edit1.Text; //字元串

   ps:=pchar(s); //轉成pchar類型,

   len:=length(s);//取字元串長度,占用多少位元組

   getmem(b,len);//申請記憶體,pchar,pbyte在使用前都必須要申請記憶體,因為他們是指針.

   move(ps^,b^,len);//這裡 ps^意思是pchar指向記憶體資料的第一個位元組位址,B^是表示申請記憶體的第一個位元組位址,這樣就可以一個一個位元組的移到b裡去了.

   memo1.Text:=pchar(b);//顯示.

   freemem(b);

end;

有些人遇到的困惑是為什麼 move(s,b,len)不行呢?同樣我也遇到這樣的困惑.

看了一樣move的函數源碼才明白.

procedure       Move( const Source; var Dest; count : Integer );

{$IFDEF PUREPASCAL}

var

  S, D: PChar;

  I: Integer;

begin

  S := PChar(@Source);//取記憶體位址

  D := PChar(@Dest);//取記憶體位址

  if S = D then Exit;

  if Cardinal(D) > Cardinal(S) then

    for I := count-1 downto 0 do

      D[I] := S[I]

  else

    for I := 0 to count-1 do

      D[I] := S[I];

end;

如果直接傳入s,

S := PChar(@Source);//取記憶體位址\

 就相當于取的字元串S位址的位址.

如果傳入的是ps^

S := PChar(@Source);//取記憶體位址

 就相當于取pchar 所指向字元串實際資料的位址.本篇文章來源于:開發學院 http://edu.codepub.com   原文連結:http://edu.codepub.com/2010/0120/19934.php

轉載于:http://blog.sina.com.cn/s/blog_6c969b4a0100y48r.html

繼續閱讀