posts - 315, comments - 268, trackbacks - 15

My Links

News

View Pietro Libro's profile on LinkedIn

DomusDotNet
   DomusDotNet

Pietro Libro

Tag Cloud

Article Categories

Archives

Post Categories

Blogs amici

Links

Marshal & Struct

Post nato da una discussione su forum. Grazie alla classe Marshal , è possibile, ad esempio, convertire una struct in un array di byte e viceversa. Supponiamo di avere la seguente struct, denominata con tanta fantasia, CustomStruct:

1 private struct CustomStruct
2 {
3 public byte _b1;
4 public byte _b2;
5 public char _c;
6 public uint _unsInt;
7 public ushort _unsShort;
8 9 public CustomStruct(byte b1, byte b2, char c,
10 uint unsInt,ushort unsShort)
11 {
12 _b1 = b1;
13 _b2 = b2;
14 _c = c;
15 _unsInt = unsInt;
16 _unsShort = unsShort;
17 }
18 19 /// <summary> 20 /// Converte un istanza di oggetto CustomStruct in un array di byte
21 /// </summary> 22 /// <param name="obj"></param> 23 /// <returns></returns> 24 public static byte[] ObjectToArray(object obj)
25 {
26 int len = Marshal.SizeOf(obj);
27 byte[] arrByte = new byte[len];
28 IntPtr ptr = Marshal.AllocHGlobal (len);
29 Marshal.StructureToPtr(obj, ptr, true);
30 Marshal.Copy(ptr, arrByte, 0, len);
31 Marshal.FreeHGlobal(ptr);
32 33 return arrByte;
34 }
35 36 /// <summary> 37 /// Converte un array di byte in un istanza di oggetto CustomStruct
38 /// </summary> 39 /// <param name="bytearray"></param> 40 /// <param name="objStruct"></param> 41 public static CustomStruct ArrayToObject(byte[] bytearray)
42 {
43 CustomStruct obj = new CustomStruct();
44 int len = Marshal.SizeOf(obj);
45 IntPtr i = Marshal.AllocHGlobal(len);
46 Marshal.Copy(bytearray, 0, i, len);
47 obj = (CustomStruct)Marshal.PtrToStructure(i, obj.GetType());
48 Marshal.FreeHGlobal(i);
49 return obj;
50 }
51 }

Il codice per eseguire la conversione, è il seguente:

1 //Creo un istanza di oggetto CustomStruct e la converto in un array di byte 2 CustomStruct custStruct = new CustomStruct (10, 20, 'z',34,1);
3 byte[] arrByte = CustomStruct.ObjectToArray(custStruct);
4 5 MessageBox.Show(custStruct._unsInt.ToString());
6 7 //Creo una seconda istanza di oggetto custStruct, valorizzandola con i
8 //dati contenuti nell'array di byte precedente 9 CustomStruct custStruct2= CustomStruct.ArrayToObject(arrByte);
10 MessageBox.Show(custStruct2._unsInt.ToString());
Technorati Tag:

Print | posted on giovedì 6 marzo 2008 11:41 | Filed Under [ C# ]

Comments have been closed on this topic.

Powered by:
Powered By Subtext Powered By ASP.NET