static IntPtr BytesToAlloc (Array marshal, int length, int stride) {
IntPtr mem = Marshal.AllocHGlobal (length*stride);
if (mem == IntPtr.Zero)
throw new OutOfMemoryException ();
bool copied = false;
try {
if (marshal is byte[])
Marshal.Copy ((byte[])marshal, 0, mem, length);
else if (marshal is int[])
Marshal.Copy ((int[])marshal, 0, mem, length);
else if (marshal is char[])
Marshal.Copy ((char[])marshal, 0, mem, length);
else
throw new InvalidOperationException();
copied = true;
}
finally {
if (!copied)
Marshal.FreeHGlobal (mem);
}
return mem;
}