如何对比两个结构体是否相同?
- Delphi(Pascal) code
type TXX= packed record bUpdateUp: Boolean; end; TTestAds = packed record Len1: DWORD; Len2: DWORD; Len3: DWORD; XX: array of TXX; end;
var
s1, s2: TTestAds;
begin
//定义两个TTestAds结构,但他们赋值各不相同,如何判断他们是否相同?
if not CompareMem(@s1, @s2, SizeOf(TTestAds)) then //用CompareMem无法对比
begin
CopyMemory(@s1, @s2, SizeOf(TTestAds));
WriteLn('Update');
end;
end;
[解决办法]
带指针的结构不能这么比较的。
应该先比较Len1,Len2,Len3。如果都相同,再比较XX的长度(注意有可能为nil),最后比较xx的内容。
[解决办法]
很晚了, 大概其给我写个小例子,自己研究吧。
明天没事的话,我可以帮你研究下。。。以前还真没注意过这方面。
- Delphi(Pascal) code
procedure TForm1.Button3Click(Sender: TObject);type TXX = packed record bUpdateUp: Boolean; end; TTestAds = packed record Len1: DWORD; Len2: DWORD; Len3: DWORD; XX: array of TXX; end;var s1, s2: TTestAds; FType: TRttiType; FRecordType: TRttiRecordType; FField: TRttiField; FContext: TRttiContext; Val1, Val2: TValue; i: Integer;begin s1.Len1 := 1; s1.Len2 := 2; s1.Len3 := 3; SetLength(s1.XX, 2); s1.XX[0].bUpdateUp := True; s1.XX[1].bUpdateUp := False; s2.Len1 := 2; // RTTI反射 // FContext := TRttiContext.Create; FType := FContext.GetType(TypeInfo(TTestAds)); for FField in FType.GetFields do begin Memo1.Lines.Add('FieldType=' + FField.FieldType.ToString); //FieldType=:TTestAds.:1 if FField.FieldType.IsRecord then begin // 把这里做成函数递归吧 end; Val1 := FField.GetValue(@s1); Val2 := FField.GetValue(@s2); if Val1.IsArray then begin for i := 0 to Val1.GetArrayLength - 1 do begin Memo1.Lines.Add(Format('%s[%d] = %s', [FField.Name, i, Val1.GetArrayElement(i).ToString])); end; end else Memo1.Lines.Add(FField.Name + ' = ' + Val1.ToString); end; // FContext.Free;end;