原文:
http://www.blogcn.com/User8/flier_lu/index.html?id=3318394
在 C/C++ 代码中,大量掺杂着包括普通类型和数组的结构,如定义 PE 文件头结构的 IMAGE_OPTIONAL_HEADER 结构定义如下:
typedef
struct
_IMAGE_DATA_DIRECTORY
{
DWORD VirtualAddress;
DWORD Size;
}
IMAGE_DATA_DIRECTORY,
*
PIMAGE_DATA_DIRECTORY;
![](/Images/OutliningIndicators/None.gif)
#define
IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif) typedef
struct
_IMAGE_OPTIONAL_HEADER
{
![](/Images/OutliningIndicators/InBlock.gif)
WORD Magic;
![](/Images/OutliningIndicators/InBlock.gif)
//![](/Images/dot.gif)
![](/Images/OutliningIndicators/InBlock.gif)
DWORD NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
![](/Images/OutliningIndicators/InBlock.gif)
}
IMAGE_OPTIONAL_HEADER32,
*
PIMAGE_OPTIONAL_HEADER32;
|
|
在 C/C++ 中这样在结构中使用数组是完全正确的,因为这些数组将作为整个结构的一部分,在对结构操作时直接访问结构所在内存块。但在 C# 这类语言中,则无法直接如此使用,因为数组是作为一种特殊的引用类型存在的,如定义:
public
struct
IMAGE_DATA_DIRECTORY
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
public uint VirtualAddress;
public uint Size;
}
![](/Images/OutliningIndicators/None.gif)
public
struct
IMAGE_OPTIONAL_HEADER
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
public const int IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
![](/Images/OutliningIndicators/InBlock.gif)
public ushort Magic;
![](/Images/OutliningIndicators/InBlock.gif)
//![](/Images/dot.gif)
![](/Images/OutliningIndicators/InBlock.gif)
public uint NumberOfRvaAndSizes;
![](/Images/OutliningIndicators/InBlock.gif)
public IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
}
|
|
在 C# 中这样定义结构中的数组是错误的,会在编译时获得一个 CS0650 错误:
以下为引用:
error CS0650: 语法错误,错误的数组声明符。若要声明托管数组,秩说明符应位于变量标识符之前
|
如果改用 C# 中引用类型的类似定义语法,如
public
struct
IMAGE_OPTIONAL_HEADER
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
public const int IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
![](/Images/OutliningIndicators/InBlock.gif)
public ushort Magic;
![](/Images/OutliningIndicators/InBlock.gif)
//![](/Images/dot.gif)
![](/Images/OutliningIndicators/InBlock.gif)
public uint NumberOfRvaAndSizes;
![](/Images/OutliningIndicators/InBlock.gif)
public IMAGE_DATA_DIRECTORY[] DataDirectory = new IMAGE_DATA_DIRECTORY[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
}
|
|
则得到一个 CS0573 错误:
以下为引用:
error CS0573: “IMAGE_OPTIONAL_HEADER.DataDirectory” : 结构中不能有实例字段初始值设定项
|
因为结构内是不能够有引用类型的初始化的,这与 class 的初始化工作不同。如此一来只能将数组的初始化放到构造函数中,而且结构还不能有无参数的缺省构造函数,真是麻烦,呵呵
public
struct
IMAGE_OPTIONAL_HEADER
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
public const int IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
![](/Images/OutliningIndicators/InBlock.gif)
public ushort Magic;
![](/Images/OutliningIndicators/InBlock.gif)
public uint NumberOfRvaAndSizes;
![](/Images/OutliningIndicators/InBlock.gif)
public IMAGE_DATA_DIRECTORY[] DataDirectory;
![](/Images/OutliningIndicators/InBlock.gif)
public IMAGE_OPTIONAL_HEADER(IntPtr ptr)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
Magic = 0;
NumberOfRvaAndSizes = 0;
![](/Images/OutliningIndicators/InBlock.gif)
DataDirectory = new IMAGE_DATA_DIRECTORY[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
}
}
|
|
这样一来看起来似乎能使了,但如果使用 Marshal.SizeOf(typeof(IMAGE_OPTIONAL_HEADER)) 看看就会发现,其长度根本就跟 C/C++ 中定义的长度不同。问题还是在于结构中数组,虽然看起来此数组是定义在结构内,但实际上在此结构中只有一个指向 IMAGE_DATA_DIRECTORY[] 数组类型的指针而已,本应保存在 DataDirectory 未知的数组内容,是在托管堆中。
于是问题就变成如何将引用类型的数组,放在一个值类型的结构中。
解决的方法有很多,如通过 StructLayout 显式指定结构的长度来限定内容:
[StructLayout(LayoutKind.Sequential, Size
=
XXX)]
public
struct
IMAGE_OPTIONAL_HEADER
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
public const int IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
![](/Images/OutliningIndicators/InBlock.gif)
public ushort Magic;
![](/Images/OutliningIndicators/InBlock.gif)
public uint NumberOfRvaAndSizes;
![](/Images/OutliningIndicators/InBlock.gif)
public IMAGE_DATA_DIRECTORY DataDirectory;
}
|
|
注意这儿 StructLayout 中 Size 指定的是整个结构的长度,因为 DataDirectory 已经是最后一个字段,故而数组的后 15 个元素被保存在未命名的堆栈空间内。使用的时候稍微麻烦一点,需要一次性读取整个结构,然后通过 unsafe 代码的指针操作来访问 DataDirectory 字段后面的其他数组元素。
这种方法的优点是定义简单,但使用时需要依赖 unsafe 的指针操作代码,且受到数组字段必须是在最后的限制。当然也可以通过 LayoutKind.Explicit 显式指定每个字段的未知来模拟多个结构内嵌数组,但这需要手工计算每个字段偏移,比较麻烦。
另外一种解决方法是通过 Marshal 的支持,显式定义数组元素所占位置,如
[StructLayout(LayoutKind.Sequential, Pack
=
1
)]
public
struct
IMAGE_OPTIONAL_HEADER
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
public const int IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
![](/Images/OutliningIndicators/InBlock.gif)
public ushort Magic;
![](/Images/OutliningIndicators/InBlock.gif)
public uint NumberOfRvaAndSizes;
![](/Images/OutliningIndicators/InBlock.gif)
[MarshalAs(UnmanagedType.ByValArray, SizeConst=IMAGE_NUMBEROF_DIRECTORY_ENTRIES)]
public IMAGE_DATA_DIRECTORY[] DataDirectory;
}
|
|
这种方法相对来说要优雅一些,通过 Marshal 机制支持的属性来定义值数组语义,使用起来与普通的数组区别不算太大。上述数组定义被编译成 IL 定义:
以下内容为程序代码:
.field public marshal( fixed array [16]) valuetype IMAGE_DATA_DIRECTORY[] DataDirectory
|
|
虽然类型还是 valuetype IMAGE_DATA_DIRECTORY[],但因为 marshal( fixed array [16]) 的修饰,此数组已经从引用语义改为值语义。不过这样做还是会受到一些限制,如不能多层嵌套、使用时性能受到影响等等。
除了上述两种在结构定义本身做文章的解决方法,还可以从结构的操作上做文章。
此类结构除了对结构内数组的访问外,主要的操作类型就是从内存块或输入流中读取整个结构,因此完全可以使用 CLR 提高的二进制序列化支持,通过实现自定义序列化函数来完成数据的载入和保存,如:
[Serializable]
public
struct
IMAGE_OPTIONAL_HEADER : ISerializable
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
public const int IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
![](/Images/OutliningIndicators/InBlock.gif)
public ushort Magic;
![](/Images/OutliningIndicators/InBlock.gif)
public uint NumberOfRvaAndSizes;
![](/Images/OutliningIndicators/InBlock.gif)
public IMAGE_DATA_DIRECTORY[] DataDirectory;
![](/Images/OutliningIndicators/InBlock.gif)
public IMAGE_OPTIONAL_HEADER(IntPtr ptr)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
Magic = 0;
NumberOfRvaAndSizes = 0;
![](/Images/OutliningIndicators/InBlock.gif)
DataDirectory = new IMAGE_DATA_DIRECTORY[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
}
![](/Images/OutliningIndicators/InBlock.gif)
[SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter=true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
// 完成序列化操作
}
}
|
|
这种解决方法可以将结构的载入和存储,与结构的内部表现完全分离开来。虽然结构内部保存的只是数组引用,但用户并不需关心。但缺点是必须为每个结构都编写相应的序列化支持代码,编写和维护都比较麻烦。
与此思路类似的是我比较喜欢的一种解决方法,通过一个公共工具基类以 Reflection 的方式统一处理,如:
public
class
IMAGE_OPTIONAL_HEADER : BinaryBlock
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
public const int IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
![](/Images/OutliningIndicators/InBlock.gif)
public ushort Magic;
![](/Images/OutliningIndicators/InBlock.gif)
public uint NumberOfRvaAndSizes;
![](/Images/OutliningIndicators/InBlock.gif)
public IMAGE_DATA_DIRECTORY[] DataDirectory = new IMAGE_DATA_DIRECTORY[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
}
|
|
注意原本的 struct 在这儿已经改为 class,因为通过这种方式已经没有必要非得固守值类型的内存模型。BinaryBlock 是一个公共的工具基类,负责通过 Reflection 提供类型的载入和存储功能,如
public
class
BinaryBlock
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
private static readonly ILog _log = LogManager.GetLogger(typeof(BinaryBlock));
![](/Images/OutliningIndicators/InBlock.gif)
public BinaryBlock()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
}
![](/Images/OutliningIndicators/InBlock.gif)
static public object LoadFromStream(BinaryReader reader, Type objType)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
if(objType.Equals(typeof(char)))
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
return reader.ReadChar();
}
else if(objType.Equals(typeof(byte)))
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
return reader.ReadByte();
}
//![](/Images/dot.gif)
else if(objType.Equals(typeof(double)))
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
return reader.ReadDouble();
}
else if(objType.IsArray)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
// 处理数组的情况
}
else
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
foreach(FieldInfo field in ClassType.GetFields())
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
field.SetValue(obj, LoadFromStream( ));
}
}
![](/Images/OutliningIndicators/InBlock.gif)
return true;
}
![](/Images/OutliningIndicators/InBlock.gif)
public bool LoadFromStream(Stream stream)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
return LoadFromStream(new BinaryReader(stream), this);
}
}
|
|
LoadFromStream 是一个嵌套方法,负责根据指定字段类型从流中载入相应的值。使用时只需要对整个类型调用此方法,则会自动以 Reflection 机制,遍历类的所有字段进行处理,如果有嵌套定义的情况也可以直接处理。使用此方法,类型本身的定义基本上就无需担心载入和存储机制,只要从 BinaryBlock 类型继承即可。有兴趣的朋友还可以对此类进一步扩展,支持二进制序列化机制。
此外 C# 2.0 中为了解决此类问题提供了一个新的 fixed array 机制,支持在结构中直接定义内嵌值语义的数组,如
以下内容为程序代码:
struct data { int header; fixed int values[10]; }
|
|
此结构在编译时由编译器将数组字段翻译成一个外部值类型结构,以实现合适的空间布局,如
.
class
private
sequential ansi
sealed
beforefieldinit data
extends [mscorlib]System.ValueType
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
.class sequential ansi sealed nested public beforefieldinit '<values>e__FixedBuffer0'
extends [mscorlib]System.ValueType
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif) ![](/Images/OutliningIndicators/ContractedSubBlock.gif) {
.pack 0
.size 40
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 [img]/images/wink.gif[/img]
.field public int32 FixedElementField
} // end of class '<values>e__FixedBuffer0'
![](/Images/OutliningIndicators/InBlock.gif)
.field public int32 header
.field public valuetype data/'<values>e__FixedBuffer0' values
.custom instance void [mscorlib]System.Runtime.CompilerServices.FixedBufferAttribute::.ctor(class [mscorlib]System.Type, int32) = ( )
}
//
end of class data
|
|
可以看到 values 字段被编译成一个值类型,而值类型本身使用的是类似于上述第一种解决方法的思路,强行限制结构长度。而在使用时,也完全是类似于第一种解决方法的 unsafe 操作,如对此数组的访问被编译成 unsafe 的指针操作:
以下内容为程序代码:
// 编译前 for(int i=0; i<10; i++) d.values[i] = i;
// 编译后 for(int i=0; i<10; i++) &data1.values.FixedElementField[(((IntPtr) i) * 4)] = i;
|
|
不幸的是这种方式必须通过 unsafe 方式编译,因为其内部都是通过 unsafe 方式实现的。而且也只能处理一级的嵌套定义,如果将 IMAGE_OPTIONAL_HEADER 的定义转换过来会得到一个 CS1663 错误:
以下内容为程序代码:
error CS1663: Fixed sized buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double
|
|