Introduction
I have looked for unsafe code using structures, but unfortunately, I couldn't find any. At last, I did by myself a little example. This is the work for fast loading a byte buffer into a structure. Down on the message board, I got a suggestion for a different way. I have created an example for a second way too.
Background
I am trying to read a byte file with structured records. The only way to parse data is the structure size. I looked for samples on the internet, and I couldn't find any, even here on CodeProject. I put a lot of effort in different ways unsuccessfully. From my point of view, the following is a good solution. After Amir's remark, I have added safe pointers for the same job. Thanks Amir.
Using the Code
The code is very simple, and I don't think you would need further help. Just open the archive and use Debug mode. This is a four byte array filled with predefined values. In the end, you would get all the values from the buffer in the structure. You can run the example too, and in the end, press a key to exit from the command prompt.
The first part of the code is a demo project for fast loading into a data structure. This part uses unsafe pointers for fast data load into a structure. The second part below is a short description of a slower method and uses safe pointers to do the same task.
byte* n = (byte*)&rtg;
byte[] y = new byte[] { 17, 34, 51, 68 };
fixed (byte* g = y)
{
byte* a = n;
byte* b = g;
for (int i = 0; i < y.Length; i++)
{
*a = *b;
a++; b++;
}
}
Safe pointers use the Marshal
class to map pointers and structures.
IntPtr safePrt = Marshal.AllocCoTaskMem(Marshal.SizeOf(rtg));
Marshal.Copy(y, 0, safePrt, y.Length);
rtg = (Rect) Marshal.PtrToStructure(safePrt, typeof(Rect));
Using Direct Type Casting
I got a good example from Lukas, and I think this is the fastest one. When I started this example, it was just for loading binary structures. This third example shows direct unsafe MEM <-> MEM copy. The key advantage is minimal code to write and fast execution.
Rect* pRect = (Rect*)g;
rtg = *pRect;
History
- Demo project V3.0: Current - added direct type casting
- Demo project V2.0
- Demo project V1.0