C# 非托管结构的字段级比较
出于测试目的,我想比较从非托管代码封送的两个结构(未知类型T) 因为它们可能在非托管表示中包含一些打包,所以不适合将整个结构转换为字节数组,然后逐字节比较:C# 非托管结构的字段级比较,c#,struct,marshalling,alignment,C#,Struct,Marshalling,Alignment,出于测试目的,我想比较从非托管代码封送的两个结构(未知类型T) 因为它们可能在非托管表示中包含一些打包,所以不适合将整个结构转换为字节数组,然后逐字节比较: int size = Marshal.SizeOf(typeof(T)); IntPtr buf1 = Marshal.AllocHGlobal(size); // FreeHGlobal omitted for simplicity IntPtr buf2 = Marshal.AllocHGlob
int size = Marshal.SizeOf(typeof(T));
IntPtr buf1 = Marshal.AllocHGlobal(size); // FreeHGlobal omitted for simplicity
IntPtr buf2 = Marshal.AllocHGlobal(size);
byte[] array1 = new byte[size];
byte[] array2 = new byte[size];
Marshal.StructureToPtr(st1, buf1, false);
Marshal.StructureToPtr(st2, buf2, false);
Marshal.Copy(buf1, array1, 0, size);
Marshal.Copy(buf2, array2, 0, size);
// inapropriate
for (int i = 0; i < size; ++i)
{
if (array1[i] != array2[i]) { return false; }
}
return true;
int size=Marshal.SizeOf(typeof(T));
IntPtr buf1=Marshal.AllocHGlobal(大小);//为了简单起见,省略了FreeHGlobal
IntPtr buf2=Marshal.AllocHGlobal(大小);
字节[]数组1=新字节[大小];
字节[]数组2=新字节[大小];
Marshal.StructureToPtr(st1,buf1,false);
Marshal.StructureToPtr(st2,buf2,false);
封送处理副本(buf1,数组1,0,大小);
封送处理副本(buf2,数组2,0,大小);
//不合时宜
对于(int i=0;i
我认为有必要逐项比较
由于反射,我可以枚举FieldInfo,然后使用Marshal.OffsetOf方法可以获得字段的偏移量
然而,不幸的是,我不知道如何获得字段的大小。
没有它,我想我无法比较两个领域消除包装的影响
foreach (var fieldInfo in typeof(T).GetFields())
{
int offset = (int)Marshal.OffsetOf(typeof(T), fieldInfo.Name);
int fieldSize = ...; // I need this
for (int i = offset; i < offset + fieldSize; ++i)
{
if (array1[i] != array2[i]) { return false; }
}
}
return true;
foreach(typeof(T).GetFields()中的var fieldInfo)
{
int offset=(int)Marshal.OffsetOf(typeof(T),fieldInfo.Name);
int fieldSize=…;//我需要这个
用于(int i=偏移量;i<偏移量+字段大小;++i)
{
如果(array1[i]!=array2[i]){返回false;}
}
}
返回true;
有没有办法做到这一点?
还是有更好的方法来比较非托管结构
注意:
字段类型是任意的(可以是原始整数、数组、字符串、枚举、结构等)。您可以使用
封送.SizeOf(fieldInfo.FieldType)
另外,这两个结构是否可以进行不同的打包?因为如果不是这样,包装不是变得无关紧要了吗?你能举一个例子说明打包意味着直接逐字节比较会给你错误的答案吗?我假设在分配内存时,它是清零的——因此任何未使用的字节(由于填充)都将为零,因此在两个数组中相等