Here's a few methods that work on formatted types (class or struct with the
StructLayout attribute applied):

static byte[] ObjectToByteArray( object o )
{
    GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned);

    try
    {
        IntPtr pBuf = h.AddrOfPinnedObject();
        int cb = Marshal.SizeOf(o);
        byte[] objBytes = new byte[cb];
        Marshal.Copy(pBuf, objBytes, 0, cb);
        return(objBytes);
    }
    finally
    {
        h.Free();
    }
}

static object ByteArrayToObject( byte[] buf, Type targetType )
{
    object o = FormatterServices.GetUninitializedObject(targetType);
    GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned);

    try
    {
        IntPtr pBuf = h.AddrOfPinnedObject();
        Marshal.Copy(buf, 0, pBuf, buf.Length);
        return(o);
    }
    finally
    {
        h.Free();
    }
}

Usage would be something like:

[StructLayout(LayoutKind.Sequential, Pack=4)]
struct Point
{
    public int x;
    public int y;
    public int z;
}

Point p = new Point();
byte[] pointData = ObjectToByteArray(p);
...
Point p2 = (Point)ByteArrayToObject(pointData, typeof(Point));

-Mike
http://staff.develop.com/woodring
http://www.develop.com/devresources


----- Original Message -----
From: "Mark Bugeja" <[EMAIL PROTECTED]>
To: <[EMAIL PROTECTED]>
Sent: Wednesday, September 18, 2002 6:32 PM
Subject: Re: [ADVANCED-DOTNET] Casting


> Hi Pierre,
>
> There are a couple of methods you can use depending on what exactly you
> are trying to achieve.
>
> One method involves uses the serialization to do all of the work for
> you. Mike Woodring covered this a while ago in his post:
>
> http://discuss.develop.com/archives/wa.exe?A2=ind0101D&L=DOTNET&P=R16111
> &I=-3
>
> Alternatively, if your ultimate goal is to pass the data through an
> iterop call (PINVOKE, etc.) you could look at leveraging the interop
> services further. You won't get a true dynamic_cast type behaviour from
> this method because you're required to know the type before the calls
> are made, but it will allow you to write generic code. If the struct is
> blittable, you could simply pin the struct (see
> System.Runtime.InteropServices.GCHandle.Alloc) and pass it directly to
> the method call. Also, the PtrToStructure and StructureToPtr methods on
> the System.Runtime.InteropServices.Marshal class can be quite useful for
> this kind of thing.
>
> Cheers,
>
> Mark.
>

You can read messages from the Advanced DOTNET archive, unsubscribe from Advanced 
DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to