简体   繁体   English

将二进制数据直接写入结构体的C#/ .net等价物是什么?

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

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 (ie first 32 bytes to name, next 2 bytes to attrib, etc). 从我收集的内容中,下面的c代码是读取二进制数据的“块”(等于结构的大小)并直接将其写入结构(即前32个字节到名称,接下来2个字节到attrib等)。 Is there any equivelent in C# managed code? C#托管代码中是否有任何等价物?

Please provide a code snipet showing similar outcome. 请提供显示类似结果的代码snipet。 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). 我不能仅仅使用.net序列化/去除化,因为我将处理遗留的现有文件(改变格式是不可行的)。

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 . 我想你在询问StructLayoutAttributeFieldOffsetAttribute

Example (snippet) from MSDN site: 来自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; 
}

Have a look at Marshalling, it is IMHO what you are looking for. 看看编组,恕我直言,你在寻找什么。

This link has an in-depth view of structs in C#: 此链接深入了解C#中的结构:

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

Additional info may be found at MSDN's Marshal Class documentation: 其他信息可以在MSDN的Marshal Class文档中找到:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM