delphi中string,pchar,array of char,pointer,Pbyte,array of byte之间的转化

写程序时,老是被几个数据类型搞的晕头转向,现在总结一下。

基本上都是从网上查的,但又不是在一个地方,所以标记成‘转载’但又不好写从哪里转载的。有抄袭请见谅。

var
s:string;
p:pchar;
a:array[1..20] of char;
那么三者之间的转换如下:
1、字符串到PChar
    p:=PChar(s);
2、PChar到字符串
    s:=p;
3、PChar到字符数组
    StrCopy(@a,p);
4、字符数组到PChar
    PChar(@a);
5、字符串与字符数组之间的转换就只有通过PChar来中转了。

StrCopy(@a,PChar(s));



下面给出一个测试例子。
procedure TForm1.Comm1ReceiveData(Sender: TObject; Buffer: Pointer;
  BufferLength: Word);
var
  tmpStr, tmpRes: string;
  P1: array of char;
  Pb: pbyte;
  B: array[0..255] of byte;
  BB: array of byte; //定义接收COM数据的字节数组
begin
  tmpStr := PChar(Buffer);//Pointer转字符串, 直接PChar即可。
  mmo1.Lines.Add( tmpStr );


  //StrCopy(@B, PChar(Buffer)); //这样就实现了转化
  StrCopy(@B, (Buffer)); //这样就实现了转化
  mmo2.Lines.Add(  pchar(@B) );
  //mmo2.Lines.Add( '直接转:' + pchar(Buffer) ); //这样转会出错,但不是一定
  
  GetMem(Pb, BufferLength + 1);//申请内存,pchar,pbyte在使用前都必须要申请内存,因为他们是指针.
  //FillChar(Pb^, BufferLength + 1, 0);//一定要先清空内存,这样才能出现以#0结束的字符
  ZeroMemory(PB, BufferLength + 1);
  Move(Buffer^, Pb^, BufferLength); 
  //StrCopy(@Pb, PChar(Buffer));
  mmo1.Lines.Add( FloatToStr(BufferLength) + '长度' +  string(Pb) );
  FreeMem(Pb); {}
  
  SetLength(tmpRes, BufferLength);
  Move(Buffer^, tmpRes[1], BufferLength);
  mmo1.Lines.Add('用字符:' + tmpRes);


  Setlength(P1, bufferLength + 1);//长度+1解决问题,动态字符数组
  Move(Buffer^, P1[0], BufferLength);
  mmo2.Lines.Add( pchar(P1) );
  
  Setlength(BB, bufferLength + 1);//长度+1解决问题,动态字符数组
  Move(Buffer^, BB[0], BufferLength);
  mmo2.Lines.Add( 'BB' + pchar(BB) );

end;

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值