我使用PtrToStructure函数(在vb.NET中)从有效指针成功提取了一个结构对象,问题是字段“FrameRects”与从C ++示例获得的值相比具有无效值:
vb.NET代码是:
StructLayout(LayoutKind.Explicit,pack:= 1,CharSet:= CharSet.Ansi)> _“
Public Structure myStruct
<FieldOffset(0)> _
Dim Width As UInt32 ' 350 correct
<FieldOffset(4)> _
Dim Height As UInt32 ' 466 correct
<FieldOffset(8)> _
Dim Frames As UInt32 ' 115 correct
<FieldOffset(12)> _
Dim FrameNum As UInt32 ' 1 correct
<FieldOffset(20)> _
Dim FrameRate As UInt32 ' 15 correct
<FieldOffset(24)> _
Dim FrameRateDiv As UInt32 ' 1 correct
<FieldOffset(28)> _
Dim ReadError As UInt32 ' 0 correct
<FieldOffset(32)> _
Dim OpenFlags As Integer ' 0 correct
<FieldOffset(16)> _
<MarshalAs(UnmanagedType.Struct)> _
Dim FrameRects As RECT ' the problem is located here
<FieldOffset(36)> _
Dim NumRects As UInt32 ' 0 correct
<FieldOffset(44)> _
Dim FrameChangePercent As UInt32 ' 0 correct
End Structure
“StructLayout(LayoutKind.Explicit,pack:= 1,CharSet:= CharSet.Ansi)&gt; _
Public Structure RECT
<MarshalAs(UnmanagedType.I4)> _
<FieldOffset(0)> _
Dim Left As Integer ' gives me -1 but it must be 0 (in C++ sample)
<MarshalAs(UnmanagedType.I4)> _
<FieldOffset(4)> _
Dim Top As Integer ' gives me 15 but it must be 0 (in C++ sample)
<MarshalAs(UnmanagedType.I4)> _
<FieldOffset(8)> _
Dim Width As Integer ' gives me 1 but it must be 0 (in C++ sample)
<MarshalAs(UnmanagedType.I4)> _
<FieldOffset(12)> _
Dim Height As Integer ' gives me 0 and it is 0 (in C++ sample)
End Structure
C ++代码是:
struct myStruct
{
U32 Width; // U32 is unsigned integer
U32 Height;
U32 Frames;
U32 FrameNum;
U32 FrameRate;
U32 FrameRateDiv;
U32 ReadError;
OPEN_FLAGS OpenFlags; // integer
RECT_ARRAY FrameRects;
U32 NumRects;
U32 FrameChangePercent;
};
struct RECT
{
S32 Left; // S32 is singed integer
S32 Top;
S32 Width;
S32 Height;
};
答案 0 :(得分:0)
FrameRate的字段偏移不应该是16而不是20吗?之后的一切都向下移了4个字节?直到你到达FrameRects,它应该是32?由于FrameRects是16字节,NumRects应该是48?
但是,既然您的结构中的所有内容都是键入和顺序的,那么为什么不使用
<StructLayout(LayoutKind.Sequential)>
而不是
StructLayout(LayoutKind.Explicit, pack:=1, CharSet:=CharSet.Ansi)>