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?
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.
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.
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.
The bytearray class is a mutable sequence of integers in the range of 0 to 256.
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.
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