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.
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.
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.
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.
The bytearray class is a mutable sequence of integers in the range of 0 to 256.
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.)
You can use a fixed-size array:
unsafe struct SomeBytes {
public fixed byte b[320];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With