An analysis of C # file pattern reading and writing structure body

Source: Internet
Author: User

has been studying the. Net Micro Framework font file (TINYFNT), because the Tinyfnt file header has a section of descriptive data, so want to define a structure, like VC directly read out from the file, so as to save the flow of parsing is very troublesome.

Did not think in the absence of direct instructions, presumably the designers think that the provision of streaming and serialization technology, all problems can be solved.

In the middle of the structure is a more complex things, there are many need to set the parameters, otherwise it is easy to make mistakes. Here is a description of the MSDN section that might help you understand the structure in the C # language.

You can customize how the structure is laid out in memory by using attributes. For example, you can use the StructLayout (layoutkind.explicit) and FieldOffset properties to create layouts that are called unions in C + +.

[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]
struct TestUnion
{
[System.Runtime.InteropServices.FieldOffset(0)]
public int i;
[System.Runtime.InteropServices.FieldOffset(0)]
public double d;
[System.Runtime.InteropServices.FieldOffset(0)]
public char c;
[System.Runtime.InteropServices.FieldOffset(0)]
public byte b;
}

In the previous code snippet, all the fields in TestUnion start from the same location in memory.

The following is another example of a field starting at another location that is explicitly set.

[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]
struct TestExplicit
{
[System.Runtime.InteropServices.FieldOffset(0)]
public long lg;
[System.Runtime.InteropServices.FieldOffset(0)]
public int i1;
[System.Runtime.InteropServices.FieldOffset(4)]
public int i2;
[System.Runtime.InteropServices.FieldOffset(8)]
public double d;
[System.Runtime.InteropServices.FieldOffset(12)]
public char c;
[System.Runtime.InteropServices.FieldOffset(14)]
public byte b;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.