Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

c#

.net

The exact structure of the struct is not important.

From what I gather the following 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);
. . .
}
like image 256
Gerald Davis Avatar asked Jan 26 '26 05:01

Gerald Davis


2 Answers

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; 
}
like image 173
myermian Avatar answered Jan 27 '26 19:01

myermian


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

like image 41
FuePi Avatar answered Jan 27 '26 19:01

FuePi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!