开发者

What is the C# / .net equivalent of writing binary data directly to a struct?

开发者 https://www.devze.com 2023-01-25 07:15 出处:网络
The exact structure of the struct is not important. From what I gather the followi开发者_JAVA技巧ng c code is reading a \"chunk\" of binary data (equal to the size of the struct) and directly writing

The exact structure of the struct is not important.

From what I gather the followi开发者_JAVA技巧ng c code is reading a "chunk" of binary data (equal to the size of the struct) and directly writing that to a struct (i.e first 32 bytes to name, next 2 bytes to attrib, etc). Is there any equivelent in C# managed code?

Please provide a code snipet showing similar outcome. To save time you can simplify the to only a few elements and assume the appropriate filestream type object is already initialized.

Note: I will be consuming an existing legacy data file so the formatting/packing of the existing data file is important. I can't for example just use .net serialization / deserization because I will be processing legacy existing files (changing format is not feasible).

typedef struct _PDB 
{
   char name[32];
   unsigned short attrib;
   unsigned short version;
   unsigned int created;
   unsigned int modified;
   unsigned int backup;
   unsigned int modNum;
   unsigned int nextRecordListID;
   unsigned short numRecs;
} PDB;

void getFileType(FILE *in) 
{
   PDB p;
   fseek(in, 0, SEEK_SET);
   fread(&p, sizeof(p), 1, in);
. . .
}


I think you're asking about the StructLayoutAttribute and the FieldOffsetAttribute.

Example (snippet) from MSDN site:

[StructLayout(LayoutKind.Explicit, Size=16, CharSet=CharSet.Ansi)]
public class MySystemTime 
{
   [FieldOffset(0)]public ushort wYear; 
   [FieldOffset(2)]public ushort wMonth;
   [FieldOffset(4)]public ushort wDayOfWeek; 
   [FieldOffset(6)]public ushort wDay; 
   [FieldOffset(8)]public ushort wHour; 
   [FieldOffset(10)]public ushort wMinute; 
   [FieldOffset(12)]public ushort wSecond; 
   [FieldOffset(14)]public ushort wMilliseconds; 
}


Have a look at Marshalling, it is IMHO what you are looking for.

This link has an in-depth view of structs in C#:

http://www.developerfusion.com/article/84519/mastering-structs-in-c/

Additional info may be found at MSDN's Marshal Class documentation:

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消