I managed to use generics via Marshal.PtrToStructrue and Marshal.StructureToPtr but these do not perform as good as the explicit methods (without using generics).
static unsafe T BytesToStruct<T>(byte[] arr) where T : struct { T t; fixed (byte* parr = arr) { t = (T)Marshal.PtrToStructure((IntPtr)parr, typeof(T)); } return t; } static unsafe byte[] StructToBytes<T>(T t) where T : struct { byte[] arr = new byte[Marshal.SizeOf(typeof(Header))]; fixed (byte* parr = arr) { Marshal.StructureToPtr(t, (IntPtr)parr, false); } return arr; } -----Original Message----- From: Discussion of advanced .NET topics. [mailto:[EMAIL PROTECTED] On Behalf Of עידו שמואלסון Sent: Tuesday, November 15, 2005 9:08 AM To: ADVANCED-DOTNET@DISCUSS.DEVELOP.COM Subject: [ADVANCED-DOTNET] Generics and 'fixed' Hi, I'm have a code that converts a struct to byte[] and vise versa. When I tried to upgrade it to accept any struct using generics (<T> … where : struct) I get the following compile error: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T') Here is my code sample: static unsafe Header BytesToHeader(byte[] arr) { Header header; fixed (byte* parr = arr) { header = *((Header*)parr); } return header; } static unsafe byte[] HeaderToByte(Header header) { byte[] arr = new byte[sizeof(Header)]; fixed (byte* parr = arr) { *((Header*)parr) = header; } return arr; } static unsafe T BytesToHeader<T>(byte[] arr) where T : struct { T t; fixed (byte* parr = arr) { t = *((T*)parr); // -- > compile error } return t; } struct Header { public int A; } Best Regards, Ido Samuelson Senior Consultant Advantech – Microsoft Division (Magen) [EMAIL PROTECTED] =================================== This list is hosted by DevelopMentor® http://www.develop.com View archives and manage your subscription(s) at http://discuss.develop.com =================================== This list is hosted by DevelopMentor® http://www.develop.com View archives and manage your subscription(s) at http://discuss.develop.com