Re: Copy a buffer to a structure with an offset

From: Tom Shelton (tom_at_mtogden.com)
Date: 04/30/04


Date: Fri, 30 Apr 2004 00:24:33 -0700

On 2004-04-29, Brad <barebrad@hotpop.com> wrote:
> Using vb.net, I am attempting to copy a byte array buffer to a
> structure but need to specify an offset, in bytes, from the top of the
> structure. I have studied the Marshal class but it appears I can only
> specify the structure name...

I would do it in c# since you can just use a pointer :) But, if you
must do this in VB.NET - here are a couple of ideas... No real tested code,
since I'm on my Linux box tonight - but maybe something that would be
useful... I've never attempted this, so this might not work - so I'm
sort of sticking my neck out here with this stream of conciousness thing ;)

Look at the Marshal.StructureToPtr method...
Look at the Marshal.AllocHGlobal method...
Look at the Marshal.FreeHGlobal method...
Look at the Marshal.Copy method...
Look at the Marshal.PtrToStructure...

Structure TheStruct
        ...
End Structure

Dim ts As TheStruct

Dim mem As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ts))
Dim offset As IntPtr = new IntPtr(mem.ToInt32() + youroffset)
Marshal.Copy(sourceArray, 0, offset, sourceArray.Length)
ts = CType(Marshal.PtrToStructure(mem), TheStruct)
Marshal.FreeHGlobal(mem)

HTH - if not... Well, let us know and maybe we can come up with a
better more workable plan - like writing this function in C# and calling
it from VB.NET :)

-- 
Tom Shelton [MVP]
Powered By Gentoo Linux 1.4
Your picture of the world often changes just before you get it into focus.


Relevant Pages