procedure TForm1.Button1Click(Sender: TObject);
var
buf1: array of char;
TmpStr: string;
TmpOrd: Word;
begin
SetLength(buf1, 2);
buf1[0] := '@';
buf1[1] := '2';
TmpStr := string(copy(buf1, 1, 1));
//TmpOrd := Ord(TmpStr[1]);
Edit1.Text := TmpStr;
//ShowMessage(IntToStr(TmpOrd));
ShowMessage(Edit1.Text);
end;
更正:
问题并不是出在TmpStr := string(copy(buf1, 1, 1));而是出在Edit1.Text := TmpStr; 因为ShowMessage(string(copy(buf1, 1, 1)));是正确的,Edit1.Text在赋值后指针没改,说明是复制了字符串,而不是引用了字符串。 跟进DCU看Edit1.Text := TmpStr;执行了下列函数:
procedure TControl.SetTextBuf(Buffer: PChar);
begin
Perform(WM_SETTEXT, 0, Longint(Buffer)); //这句拷贝了字符串,引起出错。
Perform(CM_TEXTCHANGED, 0, 0);
end;
procedure TControl.DefaultHandler(var Message);
var
P: PChar;
begin
with TMessage(Message) do
case Msg of
...
WM_SETTEXT:
begin
P := StrNew(PChar(LParam)); //这句复制字符串
StrDispose(FText);
FText := P;
SendDockNotification(Msg, WParam, LParam);
end;
end;
end;
function StrNew(const Str: PChar): PChar;
var
Size: Cardinal;
begin
if Str = nil then Result := nil else
begin
Size := StrLen(Str) + 1; //这句查找字符串结束符来计算字符长度,并加1。
Result := StrMove(StrAlloc(Size), Str, Size); //拷贝字符。
end;
end;