写程序时,老是被几个数据类型搞的晕头转向,现在总结一下。
基本上都是从网上查的,但又不是在一个地方,所以标记成‘转载’但又不好写从哪里转载的。有抄袭请见谅。
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;