Marshal.PtrToStructure skipping bytes

G

Guest

Hello,
I have a strange situation using .Net FW 1.1. I want to use
Marshal.PtrToStructure to fill the structure below. The first 3 fields
get filled correctly: ulStruct describes how big the structure is in
bytes (120 bytes, assuming 32-bit IntPtrs), pWmSnapshot gets 0, and
usNumWmSnapshots gets 0. The next field, pICView, is a pointer to
another structure, and gets filled with some garbage location, which is
actually the lower 2 bytes of the real location, and the 2 bytes of the
next field, usNumViews. The usNumViews field is then filled with the 2
bytes that were supposed to go into usItemType, and all subsequent
fields are off by those 2 bytes.

If I manually extract the structure from the pointer, using
Marshal.ReadInt32, ReadInt16, ReadIntPtr, and PtrToStringAnsi,
everything is fine. That is, if I do Marshal.ReadIntPtr(ptr_to_struct,
10) it reads the correct location for pICView.

I've tried making the pICView field an integer (MarshalAs U4), and it
skips the same 2 bytes.

I haven't had any other problems using PtrToStructure on other
structures, just this one hiccup. Any ideas?

Thanks,
Adam

Structure:

<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi)> _
Public Structure SNAPSHOTSTRUCT
<MarshalAs(UnmanagedType.U4)> Public ulStruct As Integer
Public pWmSnapshot As IntPtr 'PWMSNAPSHOTSTRUCT
<MarshalAs(UnmanagedType.U2)> Public usNumWmSnapshots As Short
Public pICView As IntPtr 'PICVIEWSTRUCT
<MarshalAs(UnmanagedType.U2)> Public usNumViews As Short
<MarshalAs(UnmanagedType.U2)> Public usItemType As Short
<MarshalAs(UnmanagedType.U4)> Public ulOpenStatus As Integer
<MarshalAs(UnmanagedType.ByValTStr, sizeconst:=17)> Public
szItemID As String
<MarshalAs(UnmanagedType.ByValTStr, sizeconst:=27)> Public
useridCheckout As String
<MarshalAs(UnmanagedType.ByValTStr, sizeconst:=27)> Public
tsCreate As String
<MarshalAs(UnmanagedType.ByValTStr, sizeconst:=27)> Public
tsModify As String
End Structure
 
G

Guest

Well, to respond to my own extremely popular topic, I found the
problem. The combination of integers, integer pointers, and shorts
(2-bytes) required me to set the packing on the structure to 2, instead
of the default 8. I can only surmise that the 3rd field, which is a
short, was properly getting only the 2 bytes, but was padded out to the
next 2. Set the packing attribute on the structure solves the problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top