其实规则很简单:
在Move前,如果目标是数组的话:
如果目标是string,无论是string或string[n]都要先SetLength。
如果目标是PChar,要用GetMemory申请内存,使用完后可别忘了FreeMemory。
简单的一点测试代码,我没有添加结果输出,自己用F8跟踪看结果吧:
// 字符串到数组的转换
procedure StringToArray;
var
s1: string;
s2: string[20];
buf1: array[0..19] of Char;
buf2: array of Char;
len1, len2: Integer;
procedure cls;
begin
s1 := '';
s2 := '';
buf1 := '';
SetLength(buf2, 0);
SetLength(buf2, 20);
len1 := 0;
len2 := 0;
end;
begin
// string to char array
cls;
s1 := 'http://MyvNet.com';
len1 := Length(s1);
len2 := Length(buf1);
Move(s1[1], buf1, Min(len1, len2));
// string to dynamic char array
cls;
s1 := 'http://MyvNet.com';
len1 := Length(s1);
len2 := Length(buf2);
Move(s1[1], buf2[0], Min(len1, len2));
// string array to char array
cls;
s2 := 'http://MyvNet.com';
len1 := Length(s2);
len2 := Length(buf1);
Move(s2[1], buf1, Min(len1, len2));
// string array to dynamic char array
cls;
s2 := 'http://MyvNet.com';
len1 := Length(s2);
len2 := Length(buf2);
Move(s2[1], buf2[0], Min(len1, len2));
cls;
end;
// 数组到字符串的转换
procedure ArrayToString;
var
s1: string;
s2: string[20];
buf1: array[0..19] of Char;
len1, len2: Integer;
procedure cls;
begin
s1 := '';
s2 := '';
buf1 := '';
SetLength(buf2, 0);
SetLength(buf2, 20);
len1 := 0;
end;
begin
// char array to string
cls;
buf1 := 'http://MyvNet.com';
len1 := Length(buf1);
SetLength(s1, len1);
Move(buf1, s1[1], len1);
// char array to string array
cls;
buf1 := 'http://MyvNet.com';
len1 := Length(buf1);
SetLength(s2, len1);
Move(buf1, s2[1], len1);
// or
//Move(buf1, s2[1], len1);
//s2[0] := Chr(len1);
// dynamic char array to string
cls;
buf1 := 'http://MyvNet.com';
Move(buf1, buf2[0], Length(buf1));
len1 := Length(buf2);
SetLength(s1, len1);
Move(buf2[0], s1[1], len1);
// dynamic char array to string array
cls;
buf1 := 'http://MyvNet.com';
Move(buf1, buf2[0], Length(buf1));
len1 := Length(buf2);
SetLength(s2, len1);
Move(buf2[0], s2[1], len1);
// or
//Move(buf2[0], s2[1], len1);
//s2[0] := Chr(len1);
cls;
end;
// PChar和数组的转换
procedure TForm1.PCharAndArray;
var
pc: PChar;
buf1: array[0..19] of Char;
buf2: array of Char;
len1: Integer;
procedure cls;
begin
pc := '';
buf1 := '';
SetLength(buf2, 0);
SetLength(buf2, 20);
len1 := 0;
end;
begin
// PChar to array
cls;
pc := 'http://MyvNet.com';
len1 := Length(pc);
Move(pc^, buf1, len1);
// PChar to dynamic array
cls;
pc := 'http://MyvNet.com';
len1 := Length(pc);
Move(pc^, buf2[0], len1);
// array to PChar
cls;
buf1 := 'http://MyvNet.com';
len1 := Length(buf1);
pc := GetMemory(len1);
Move(buf1, pc^, len1);
FreeMemory(pc);
// dynamic array to PChar
cls;
buf1 := 'http://MyvNet.com';
Move(buf1, buf2[0], Length(buf1));
len1 := Length(buf2);
pc := GetMemory(len1);
Move(buf2[0], pc^, len1);
FreeMemory(pc);
cls;
end;
联系客服