3

我想转换struct object into byte[]vice versa在 windows phone 7 应用程序中使用此代码,它在 windows 窗体应用程序中完美运行,但在 windows phone 应用程序中不起作用,错误是

'System.Runtime.InteropServices.Marshal' does not contain a definition for 'AllocHGlobal'   

'System.Runtime.InteropServices.Marshal' does not contain a definition for 'FreeHGlobal'

我的代码是

public static byte[] getBytes(object o)
        {
            int size = Marshal.SizeOf(o);
            byte[] arr = new byte[size];
            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(o, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);
            return arr;
        }

        public static object getStruct(byte[] arr, object o)
        {            
            int size = Marshal.SizeOf(o);
            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.Copy(arr, 0, ptr, size);
            o = (object)Marshal.PtrToStructure(ptr, o.GetType());
            Marshal.FreeHGlobal(ptr);
            return o;
        }    
4

0 回答 0