在实际编程中,经常会用到Buffer,当string作为Buffer传值时需要注意的是
1, string的值的起始索引是1,千万记住!
2, 有时候需要先告诉系统去开辟出内存空间,用SetLength函数。
如下代码,示范了再Move、 WriteBuffer、 ReadBuffer时候的用法:
- unit Unit3;
- interface
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs, StdCtrls;
- type
- TForm3 = class(TForm)
- Memo1: TMemo;
- Button1: TButton;
- Button2: TButton;
- Button3: TButton;
- Button4: TButton;
- procedure Button1Click(Sender: TObject);
- procedure Button2Click(Sender: TObject);
- procedure FormCreate(Sender: TObject);
- procedure FormDestroy(Sender: TObject);
- procedure Button3Click(Sender: TObject);
- procedure Button4Click(Sender: TObject);
- private
- { Private declarations }
- FMemoryStream: TMemoryStream;
- FBuffer: string;
- public
- { Public declarations }
- end;
- var
- Form3: TForm3;
- implementation
- {$R *.dfm}
- procedure TForm3.Button1Click(Sender: TObject);
- var
- LStr: string;
- LLen: Integer;
- begin
- LStr := '太棒了!Hello, 世界 我太爱你了';
- LLen := Length(LStr);
- FMemoryStream.WriteBuffer(LLen, SizeOf(LLen));
- // 要用LStr[1], 而不是LStr
- FMemoryStream.WriteBuffer(LStr[1], LLen);
- end;
- procedure TForm3.Button2Click(Sender: TObject);
- var
- LStr: string;
- LLen: Integer;
- begin
- // 因为写入与读出在一个工程中,所以先把指针指向开头位置
- FMemoryStream.Position := 0;
- FMemoryStream.ReadBuffer(LLen, SizeOf(LLen));
- SetLength(LStr, LLen);
- // 要用LStr[1], 而不是LStr
- FMemoryStream.ReadBuffer(LStr[1], LLen);
- Memo1.Lines.Add(LStr);
- end;
- procedure TForm3.Button3Click(Sender: TObject);
- var
- LStr: string;
- LLen: Integer;
- LIndex: Integer;
- begin
- LStr := '世界很美好 Hello, World!';
- LLen := Length(LStr);
- // 先为FBuffer开辟出空间
- SetLength(FBuffer, SizeOf(LLen) + LLen);
- LIndex := 1;
- // FBuffer的起始位置为1
- Move(LLen, FBuffer[1], SizeOf(LLen));
- // 计算Buffer指针的移动位置
- Inc(LIndex, SizeOf(LLen));
- // 要用LStr[1], 而不是LStr
- Move(LStr[1], FBuffer[LIndex], LLen);
- end;
- procedure TForm3.Button4Click(Sender: TObject);
- var
- LStr: string;
- LLen: Integer;
- LIndex: Integer;
- begin
- LIndex := 1;
- Move(FBuffer[1], LLen, SizeOf(LLen));
- Inc(LIndex, SizeOf(LLen));
- SetLength(LStr, LLen);
- // 要用LStr[1], 而不是LStr
- Move(FBuffer[LIndex], LStr[1], LLen);
- Memo1.Lines.Add(LStr);
- end;
- procedure TForm3.FormCreate(Sender: TObject);
- begin
- FMemoryStream := TMemoryStream.Create;
- end;
- procedure TForm3.FormDestroy(Sender: TObject);
- begin
- FMemoryStream.Free;
- end;
- end.
http://blog.csdn.net/procedure1984/article/details/5419454