How to convert struct to byte array?
-
Hi Find below the structure am using struct Test { int i; string s; } struct Check { int intI; Test []structArray; } How to convert the Check structure to byte array ? Thanks in advance chandru
-
Hi Find below the structure am using struct Test { int i; string s; } struct Check { int intI; Test []structArray; } How to convert the Check structure to byte array ? Thanks in advance chandru
-
Hi Find below the structure am using struct Test { int i; string s; } struct Check { int intI; Test []structArray; } How to convert the Check structure to byte array ? Thanks in advance chandru
The following code converts the structure to bytearray. Hope this helps...
using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Pack=1)] public struct Test { public int i; public string s; } [StructLayout(LayoutKind.Sequential, Pack=1)] public struct Check { public int I; public Test [] structArray ; public int GetMySize() { int iSize = Marshal.SizeOf( I) + Marshal.SizeOf( typeof( Test)) * structArray.Length; return iSize; } public void MarshalStructToPtr(ref IntPtr ptr) { Marshal.StructureToPtr(I ,ptr, true); ptr = (IntPtr)((int)ptr + Marshal.SizeOf( I )); for( int count = 0; count < structArray.Length; count ++ ) { Marshal.StructureToPtr(structArray[count],ptr, true); ptr = (IntPtr)((int)ptr + Marshal.SizeOf( structArray[count] )); } } } class ConvertStructToByteArray { public void Convert() { Test test1 = new Test(); test1.i = 2; test1.s = "test"; Check objCheck = new Check(); objCheck.I =10; objCheck.structArray = new Test[1]; objCheck.structArray[0] = test1; int Size = objCheck.GetMySize() ; IntPtr pCheck = Marshal.AllocHGlobal((int)Size ); IntPtr Temp = pCheck; objCheck.MarshalStructToPtr( ref Temp); byte[] bytearrCheck = new byte[ Size]; Marshal.Copy( pCheck , bytearrCheck , 0,(int)Size); Marshal.FreeHGlobal( pCheck ); } }