Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a byte[] to a record

Tags:

delphi

In C++ it's done like that:

tPacket * packet = (tPacket *)data; //data is byte[] array; tPacket is a structure

In C#:

tPacket t = new tPacket();
GCHandle pin = GCHandle.Alloc(data, GCHandleType.Pinned);
t = (tPacket)Marshal.PtrToStructure(pin.AddrOfPinnedObject(), typeof(tPacket));
pin.free();

Data is a byte array used as a receive buffer after a packet is received over TCP. That code puts data in an instance of tPacket (a structure) so I can access the structure later.

How is it done in Delphi?

like image 815
Ivan Prodanov Avatar asked May 18 '09 17:05

Ivan Prodanov


People also ask

How do you assign a byte value?

We can assign any int literal that falls in the range of byte to a byte variable. For example, byte b1 = 125; byte b2 = -11; If we assign an int literal to a byte variable and the value is outside the range of the byte data type, Java generates a compiler error.

What is byte array format?

ByteArray is an extremely powerful Class that can be used for many things related to data manipulation, including (but not limited to) saving game data online, encrypting data, compressing data, and converting a BitmapData object to a PNG or JPG file.

How does a byte array work?

A byte is 8 bits (binary data). A byte array is an array of bytes (tautology FTW!). You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.

What is byte array size?

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


1 Answers

You can also use the absolute keyword to force both structures to share the same memory address:

var
  Data: array[1..SizeOf(TMyStruct)] of byte;
  s : TMyStruct absolute Data;

Any data written to S is also available as Data without having to perform a move or pointer casting.

like image 167
skamradt Avatar answered Nov 16 '22 15:11

skamradt