如何在delphi中将记录转换为字节数组并提取回值?

如何在delphi中将记录转换为字节数组并提取回值?,delphi,delphi-xe3,indy10,Delphi,Delphi Xe3,Indy10,我使用move命令对记录值进行一个字节到字符串的转换,但当我添加更多值时,它会显示垃圾值。这是密码 interface type tcommand = ( cmd_login, cmd_logout, cmd_userinfo, cmd_removeuser, cmd_response ); tprotocol = record username: string; receipent_username: string;

我使用move命令对记录值进行一个字节到字符串的转换,但当我添加更多值时,它会显示垃圾值。这是密码

interface

type
  tcommand = (
    cmd_login,
    cmd_logout,
    cmd_userinfo,
    cmd_removeuser,
    cmd_response
  );

  tprotocol = record
    username: string;
    receipent_username: string;
    arr: tbytes;
    case command_id: tcommand of
      cmd_userinfo:
        (username2: shortstring; ip: shortstring; port: word); // new info
      cmd_response:
        (status: boolean);
      cmd_removeuser:
        (username_remove: shortstring);
  end;

  pprotocol = ^tprotocol;

procedure encode_packet(obj: pprotocol);
procedure decode_packet(arr1: tbytes);

implementation

procedure encode_packet(obj: pprotocol);
begin
  setlength(obj.arr, length(obj.username) * 2);
  move(obj.username[1], obj.arr[0], length(obj.username) * 2);

  setlength(obj.arr, length(obj.receipent_username) * 2);
  // SetLength(Destination, SourceSize);
  move(obj.receipent_username[1], obj.arr[1],
    length(obj.receipent_username) * 2);
  // problem starts from here
end;

procedure decode_packet(arr1: tbytes);
begin
  setlength(username, length(arr1));
  move(arr1[0], username[1], length(arr1));

  setlength(s, length(arr1));
  move(arr1[1], s[1], length(arr1));
end;
用法:

showmessage(username);
// displays correct value if recepient_username is not encoded
showmessage(s);

procedure TForm1.encodeClick(Sender: TObject); // button click
var
  obj2: pprotocol;
begin
  new(obj);
  new(obj2);
  memo1.Lines.Add('encode click');
  obj.username           := 'ahmd';
  obj.receipent_username := 'ali';

  encode_packet(obj);
  decode_packet(obj.arr);

end;

我想我必须从何处开始和停止解码字节数组进行一些索引,但我不知道怎么做?有谁能解释一下字符串是如何存储在字节数组中的(当我调试时,我看到有数字和一些nil值,如果它们与nil值混合在一起,如何从索引中获取字符串?

您可以使用move命令length*2字节在一侧进行复制,但另一侧只能使用length字节。 如果使用unicode字符串,则两侧需要使用长度*2字节

这里的另一个问题是在一个数组中逐个复制两个字符串。若要将两个字符串保存在一个数组中,那个么必须在数组中分配足够的空间,还要输入有关字符串长度的信息,并写入两个字符串的内容。如何将2个字符串放入1个字节数组的示例:

procedure test;
var
  len: integer;
  buf: array of byte;
  a,b: string;
begin
  a := 'try';
  b := 'that';

  // save
  setlength(buf, SizeOf(Char)*(Length(a)+Length(b))+8);
  len := length(a);
  move(len, buf[0], 4);
  len := length(b);
  move(len, buf[4], 4);
  move(a[1], buf[8], length(a)*SizeOf(char));
  move(b[1], buf[8+length(a)*SizeOf(char)], length(a)*SizeOf(char));

  // restore
  a := '';
  b := '';
  move(buf[0], len, 4);
  setlength(a, len);
  move(buf[4], len, 4);
  setlength(b, len);
  move(buf[8], a[1], length(a)*SizeOf(char));
  move(buf[8+length(a)*SizeOf(char)], b[1], length(a)*SizeOf(char));
end;
但我建议您不要使用指针,而是使用任何类型的序列化,例如内存流