Record의 시리얼화 및 역시리얼화(delphi)

2073 단어 Delphi
Record의 시리얼화 및 역시리얼화

TDefaultMessage = record  //    
    Ident: Integer;
    nIsZlib: Integer;
    nLength: Integer;
  end;


//      
function RecordToString(var Buf; bufSize: Integer; isZlib: Boolean): string;

//      
function StringToRecord(sData: string; var outBuf; outSize: Integer; isZlib: Boolean): Boolean;

//     
function GetNetPacket(sData: string; var defMsg: TDefaultMessage; var msgBody, msgNone: string): Boolean;


function RecordToString(var Buf; bufSize: Integer; isZlib: Boolean): string;
var
  str1: string;
begin
  SetLength(str1, bufSize);
  try
    CopyMemory(PChar(str1), PChar(@Buf), bufSize);
    if isZlib then
      Result := ZCompressStr(str1)
    else
      Result := str1;
  finally
    SetLength(str1, 0);
  end;
end;

function StringToRecord(sData: string; var outBuf; outSize: Integer; isZlib: Boolean): Boolean;
begin
  if isZlib then
    sData := ZDecompressStr(sData);

  CopyMemory(PChar(@outBuf), PChar(sData), outSize);
  Result := True;
end;

function GetNetPacket(sData: string; var defMsg: TDefaultMessage; var msgBody, msgNone: string): Boolean;
var
  len: Integer;
begin
  Result := False;
  defMsg.Ident := -1;
  msgBody := '';
  msgNone := '';
  if Length(sData) < SizeOf(TDefaultMessage) then
    Exit;

  if not StringToRecord(sData, defMsg, SizeOf(TDefaultMessage), False) then
    Exit;

  if defMsg.Ident < 0 then
    Exit;

  len := SizeOf(TDefaultMessage) + defMsg.nLength;
  if Length(sData) < len then  //    
    Exit;

  if defMsg.nLength > 0 then begin
    msgBody := Copy(sData, sizeof(TDefaultMessage) + 1, defMsg.nLength);
    if defMsg.nIsZlib > 0 then
      msgBody := ZDecompressStr(msgBody);
  end;

  //   
  if Length(sData) > len then
    msgNone := Copy(sData, len + 1, Length(sData) - len);

  Result := True;
end;


//demo:
procedure test1;
var
  defmsg: TDefaultMessage;
  sdata: string;
begin
  sdata:= RecordToString(defmsg, sizeof(TDefaultMessage), false);
  StringToRecord(sData, defmsg, sizeof(TdefaultMessage), false);
end;

좋은 웹페이지 즐겨찾기