复制不同的结构,以字节数组 [英] Copying different structs to byte arrays
问题描述
我转换成一个旧的Visual Basic程序为C#。该计划通过串行或以太网线将消息发送到一些工业机械。要做到这一点它创建的消息的字节数组。
I'm converting an old Visual BASIC program to C#. The program sends messages to some industrial machinery over a serial or ethernet line. To do this it creates a byte array of the message.
现在的问题是,有很多(〜50)不同的邮件格式,每在VB6一项定义为用户定义的类型。例如。
The problem is that there are MANY (~50) different message formats, each one defined in VB6 as a user-defined type. For example.
Public Type K_QCHECK
Header As K_HEADER3
Count As LNG4
crc As INT2
End Type
(LNG4和INT2的是自定义类型)通过运行VB6代码自动翻译工具,我得到一个C#结构:
(LNG4 and INT2's are custom types) Running the VB6 code through an automated translation tool I get a C# struct:
public struct K_QCHECK
{
public K_HEADER3 Header;
public LNG4 Count;
public INT2 crc;
}
不过老VB6的代码复制到这些字节数组与LSET。这取决于该类型代表一个连续的内存块中的假设。但在C#中的东西的方式铺设出在内存应该是一个可以实现的程序员无法访问详细的编译器。
But the old VB6 code copied these to the byte array with an LSet. This depended on the assumption that the types represented a contiguous block of memory. But in C# the way stuff is laid-out by the compiler in memory is supposed to a be an implementation detail not accessible to the programmer.
那么什么是最好的方式得到这些不同结构的内容写入的字节数组?我可以让每一个类,并给它一个CopyToByteArray方法或者操作者,但也有其中50,这样似乎是一个大量的工作。在此先感谢您的任何建议!
So what's the best way to get the contents of these different structs into a byte array? I could make each one a class and give it a CopyToByteArray method or operator but there are 50 of these so that seems like a lot of work. Thanks in advance for any suggestions!
推荐答案
这可能不是正确的解决方案,但有一个StructLayoutAttribute它可以让你定义明确该结构是如何在内存布局。
This is probably not the right solution, but there is a StructLayoutAttribute which lets you define explicitly how the struct is laid out in memory.
这篇关于复制不同的结构,以字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!