Click here to Skip to main content
15,035,723 members
Articles / Programming Languages / C#
Posted 4 Dec 2006


12 bookmarked

Load C# Class Instance or Structure from a byte[] Buffer

Rate me:
Please Sign up or sign in to vote.
2.55/5 (8 votes)
27 Apr 2007CPOL2 min read
How to can load a structure with unsafe coding and fill the structure using a byte array.


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.


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

//Gets address of y byte array
fixed (byte* g = y)
   byte* a = n;
   byte* b = g;

   //Loads y array into rtg (Rect) structure
   for (int i = 0; i < y.Length; i++)
       *a = *b;
       a++; b++;

Safe pointers use the Marshal class to map pointers and structures.

//Allocate amount of memory
IntPtr safePrt = Marshal.AllocCoTaskMem(Marshal.SizeOf(rtg));

//Copy y byte buffer into memory allocated
Marshal.Copy(y, 0, safePrt, y.Length);

//Map structure to pointer
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.

// cast the byte pointer to Rect pointer
Rect* pRect = (Rect*)g;

// assign the pointer address to the rtg variable declared outside
rtg = *pRect;

// it can be even done in one line like this:
// rtg = *((Rect*)g);


  • Demo project V3.0: Current - added direct type casting
  • Demo project V2.0
  • Demo project V1.0


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Nick Yakov
Software Developer
United Kingdom United Kingdom
MCs Computer Sciense, MBA, MCSE.
Senior Net Developer - Team Lead
Systems Architect

Comments and Discussions

GeneralTake a look at this solution Pin
Ralph Varjabedian29-Jul-08 2:38
MemberRalph Varjabedian29-Jul-08 2:38 
GeneralDetailed article Pin
Toby_19-Sep-07 3:19
MemberToby_19-Sep-07 3:19 
There's a quite nice and detailed article on this topic in the net: Mastering structs in C#

Refer to section Structs from streams in this article to find an alternative way in complete safe code, using Marshal.PtrToStructure() and GCHandle.
GeneralFastest Way [modified] Pin
Lukas Fellechner26-Apr-07 2:17
MemberLukas Fellechner26-Apr-07 2:17 
GeneralRe: Fastest Way Pin
Nick Yakov26-Apr-07 5:05
MemberNick Yakov26-Apr-07 5:05 
GeneralFree allocated memory Pin
RTate6-Dec-06 8:12
MemberRTate6-Dec-06 8:12 
GeneralRe: Free allocated memory Pin
Nick Yakov7-Dec-06 1:56
MemberNick Yakov7-Dec-06 1:56 
GeneralRe: Free allocated memory Pin
RTate7-Dec-06 5:18
MemberRTate7-Dec-06 5:18 
GeneralRe: Free allocated memory Pin
Nick Yakov7-Dec-06 20:11
MemberNick Yakov7-Dec-06 20:11 
GeneralAnother way... Pin
Amir Shimoni4-Dec-06 6:01
MemberAmir Shimoni4-Dec-06 6:01 
GeneralRe: Another way... Pin
Nick Yakov4-Dec-06 23:41
MemberNick Yakov4-Dec-06 23:41 
Generalremove sample doc Pin
Jcmorin4-Dec-06 4:09
MemberJcmorin4-Dec-06 4:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.