delphi中string,pchar,array of char,pointer,Pbyte,array of byte之間的轉化
阿新 • • 發佈:2019-02-15
下面給出一個測試例子。
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;