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

The exact structure of the structure is not important.

From what I am compiling, the following c-code reads a “piece” of binary data (equal to the size of the structure) and writes it directly to the structure (that is, first 32 bytes to name, the next 2 bytes for the attribute, etc. ) Are there any equivalents in C # managed code?

Please provide a sniper code showing a similar result. To save time, you can simplify only a few elements and assume that the corresponding filter type object is already initialized.

Note. I will use the existing old data file, so formatting / packing an existing data file is important. For example, I cannot simply use .net serialization / deserialization because I will process obsolete existing files (format change is not possible).

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);
. . .
}
+3
source share
2 answers

I think you are asking about StructLayoutAttribute and FieldOffsetAttribute .

Example (snippet) from MSDN:

[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; 
}
+7
source

Look at Marshalling, this is IMHO what you are looking for.

This link provides a detailed view of the structures in C #:

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

MSDN Marshal Class:

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

+2

Source: https://habr.com/ru/post/1775433/


All Articles