I have a Read generic function that does its job very well. It reads from a buffer of bytes and returns the specific type
public static T Read<T>()
{
// An T[] would be a reference type, and a lot easier to work with.
T[] t = new T[1];
// Marshal.SizeOf will fail with types of unknown size. Try and see...
int s = Marshal.SizeOf(typeof(T));
if (index + s > size)
// Should throw something more specific.
throw new Exception("Error 101 Celebrity");
// Grab a handle of the array we just created, pin it to avoid the gc
// from moving it, then copy bytes from our stream into the address
// of our array.
GCHandle handle = GCHandle.Alloc(t, GCHandleType.Pinned);
Marshal.Copy(dataRead, index, handle.AddrOfPinnedObject(), s);
index += s;
// Return the first (and only) element in the array.
return t[0];
}
Problem: How to do the Write function?
public static T Write<T>()
{
// An T[] would be a reference type, and a lot easier to work with.
T[] t = new T[1];
// Marshal.SizeOf will fail with types of unknown size. Try and see...
int s = Marshal.SizeOf(typeof(T));
if (index + s > size)
// Should throw something more specific.
throw new Exception("Error 101 Celebrity");
// Grab a handle of the array we just created, pin it to avoid the gc
// from moving it, then copy bytes from our stream into the address
// of our array.
GCHandle handle = GCHandle.Alloc(dataWrite, GCHandleType.Pinned);
Marshal.Copy(t, index, handle.AddrOfPinnedObject(), s); // ?? Problem
index += s;
}
“t” should be byte[] array. How do I accomplish that?
It’s a lot of code to put on SO, but here y’go. There are a few overloads for Marshal.Copy that suit your needs.