我如何在C#中固定大小的字节数组用户类型? [英] How do I make fixed-size byte array user type in C#?

查看:141
本文介绍了我如何在C#中固定大小的字节数组用户类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我转换成一个旧的Visual Basic程序为C#。这将消息发送给一些机械工业以太网。要做到这一点,把来自固定大小的用户定义的数据块的字节流。

I'm converting an old Visual BASIC program to C#. It sends messages to some industrial machinery over ethernet. To do this it assembles a stream of bytes from fixed-size user defined chunks.

大多数块很小,在C#中可以很容易地创建几个字节结构或者整形和控制使用StructLayout的,例如:

Most of these chunks are small and in C# it's easy to create structs of a few bytes or ints and control their size and layout using StructLayout's, for example

[StructLayout(LayoutKind.Sequential, Pack = 1)]

...所以,当我们进入非托管空间做一个按字节副本,我们没有字节顺序或填充的问题。

...so when we go into unmanaged space to do a bytewise copy we don't have byte order or padding problems.

但一些VB6的结构都是大阵列,例如,

But some of the VB6 structures are big arrays, for example,

Private Type SEND_MSG_BUFFER_320_BYTES
    bytes(0 To 319) As Byte  '320 bytes
End Type

和我与如何做到这一点在C#中挣扎。我可以做一个固定大小的数组中的一类,如

and I'm struggling with how to do this in C#. I can make a fixed size array in a class, e.g.,

  [StructLayout(LayoutKind.Sequential, Pack = 1)]
  public class SOME_BYTES
  {
      public byte[] b = new byte[320];
  } 



但要做到逐字节副本我需要能够发现在运行时System.Runtime.InteropServices.Marshal.SizeOf的这种规模返回 4 这一点。

有关如何做到这一点的任何建议将非常感激。

Any suggestions for how do do this will be much appreciated.

推荐答案

我觉得你想要做这样的事情:

I think you want to do something like this:

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public class SOME_BYTES
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst=320)]
        public byte[] b;
    } 



如下你会初始化它:

You would initialise it as follows:

SOME_BYTES data = new SOME_BYTES {b = new byte[320]};



然后就可以填充data.b []并使用编组来获得要发送的数据。 MarshalAs特性告诉编组编组数据时使用何种固定大小的缓冲区。

Then you can populate data.b[] and use marshalling to get the data to send. The MarshalAs attribute tells the marshaller what fixed size buffer to use when marshalling the data.

您不需要使用不安全的固定关键字做这种事情,我强烈建议你避免它。

You don't need to use the unsafe fixed keyword to do this kind of thing, and I strongly recommend that you avoid it.

这篇关于我如何在C#中固定大小的字节数组用户类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆