Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make fixed-size byte array user type in C#?

Tags:

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.

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.

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

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];
  } 

but to do the byte-wise copy I need to be able to discover the size of this at runtime and System.Runtime.InteropServices.Marshal.SizeOf returns a 4 for this.

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

like image 592
user316117 Avatar asked Jan 31 '13 15:01

user316117


People also ask

How do you assign a byte array?

Array setByte() method in Java Parameter: This method takes 3 parameters: array: This is an array of type Object which is to be updated. index: This is the index of the array which is to be updated. value: This is the byte value that is to be set at the given index of the given array.

What is byte array data type?

The bytearray() method returns a bytearray object, which is an array of bytes. It returns a mutable series of integers between 0 and 256. The source parameter of the ByteArray is used to initialize the array.

Can you compress byte array?

Compressing a byte array is a matter of recognizing repeating patterns within a byte sequence and devising a method that can represent the same underlying information to take advantage of these discovered repetitions.

What is byte array size?

The bytearray class is a mutable sequence of integers in the range of 0 to 256.


2 Answers

You can use fixed size buffers if you're okay with unsafe code, and changing your class into a struct:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct SomeBytes
{
    public fixed byte MessageData[320];
}

Personally I would try to avoid all of this if possible. If you're just sending the data over the network, why do you need to "go into unmanaged space"? Can you remove that requirement somehow? (Maybe it's fundamental - but it's not clear from your question.)

like image 103
Jon Skeet Avatar answered Sep 20 '22 00:09

Jon Skeet


You can use a fixed-size array:

unsafe struct SomeBytes {
    public fixed byte b[320];
}
like image 45
nneonneo Avatar answered Sep 22 '22 00:09

nneonneo