天天看点

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

继续阅读