Re: using generics to serialize primitives.
- From: "colin" <colin.rowe1@xxxxxxxxxxxxxxxxxx>
- Date: Wed, 21 May 2008 12:08:50 +0100
public class Sizeof<T>
{
public static bool IsBinary = typeof(T).IsPrimitive||
(typeof(T).IsValueType &&
typeof(T).StructLayoutAttribute.Pack == 1&&
typeof (T).StructLayoutAttribute.Value!= LayoutKind.Auto);
public static int Size = GetSize();
public static int GetSize()
{
if (IsBinary)
return Marshal.SizeOf(typeof(T));
return 1; //partialy safe defualt.
}
}
unsafe public static byte[] ToBytes<T>(void * ptr)
{
int bytes = Sizeof<T>.Size;
Debug.Assert(Sizeof<T>.IsBinary);
byte[] buff = new byte[bytes];
Copy((byte*)ptr, buff, 0, bytes);
return buff;
}
I wrote this unsafe method, but I never fully trusted it ...
you have to specify the generic type explicitly when you call it.
its also awkward to use as you cant take the address of a generic parameter.
it stores the size in a static field for quick access.
I ended up just using overloaded functions wich call BitConverter.
Colin =^.^=
"Brian" <Brian@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:483C27B7-18FC-4B30-960D-E57C522D8C4F@xxxxxxxxxxxxxxxx
What is the easiest way to convert primitives to a byte array? I tried the
BinaryFormatter serialization but it serializes objects so when I
serialized
an and int it took 54 bytes instead of 4. I tried something like the
following but it won't compile (I admit I use generics a lot but haven't
written many so this may be way off):
class X<T>
{
public byte[] ToByteArray(T val)
{
BinaryWriter bw = new BinaryWriter(new MemoryStream());
bw.Write(val);
BinaryReader br = new BinaryReader(bw.BaseStream);
br.BaseStream.Position = 0;
return br.ReadBytes((int)br.BaseStream.Length);
}
}
I don't want to have an overloaded method for every primitive type. Is
there
an easy way to do this...or have the overloads already been written to do
this and I am just missing it? It seems like a pretty basic task that
should
be there somewhere already.
thanks
.
- References:
- using generics to serialize primitives.
- From: Brian
- using generics to serialize primitives.
- Prev by Date: Re: WM_SETFOCUS
- Next by Date: Re: Is partial deduction of generic parameters possible
- Previous by thread: Re: using generics to serialize primitives.
- Next by thread: Earn Money Through Home Based Internet Jobs Without Any Investment, Who Can Spend Only Few ...
- Index(es):
Relevant Pages
|