StructLayout 和 FieldOffset 的未定义行为 [英] undefined behaviour with StructLayout and FieldOffset
本文介绍了StructLayout 和 FieldOffset 的未定义行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经成功地使用 PtrToStructure 函数(在 VB.NET 中)从有效指针中提取了一个结构对象,但某些对象成员的结果不正确(与 C++ 示例相比):
I have extracted with success a structure object from a valid pointer using the PtrToStructure function (in VB.NET), but the result of some object members are not correct (comparing with the C++ example):
代码是:
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(20)> _
Dim Buffer As IntPtr ' variable but correct
<FieldOffset(24)> _
Dim BufferPitch As Integer ' 1408 correct
<FieldOffset(16)> _
Dim SurfaceType As Integer ' -2147483645 correct
<FieldOffset(unknow)> _
Dim WindowWidth As UInt32 ' must be 356, tested from 0 to 230
<FieldOffset(unknow)> _
Dim WindowHeight As UInt32 ' must be 495, tested from 0 to 100
<FieldOffset(15)> _
Dim ScreenHeight As UInt32 ' 768 correct
<FieldOffset(36)> _
Dim ScreenWidth As UInt32 ' 1366 correct
<FieldOffset(44)> _
Dim ScreenDepth As UInt32 ' 32 correct
End Structure
我找不到 WindowWidth 和 WindowHeight 的 FieldOffset 参数的确切值.问题是为什么以及如何修复它们?
i can't find the exact values for the FieldOffset parameter of WindowWidth and WindowHeight. the question is why and how to fix them?
struct myStruct
{
U32 Width; // U32 = 32-bit unsigned integer
U32 Height;
VOID_PTR Buffer;
S32 BufferPitch; // 32-bit signed integer
COPY_FLAGS SurfaceType; // integer
U32 WindowWidth;
U32 WindowHeight;
U32 ScreenWidth;
U32 ScreenHeight;
U32 ScreenDepth;
}
推荐答案
这个问题解决了.通过更改位于 8 和 12 中的偏移量并将指针参数修改为另一个值.
this problem is solved. by changing the offset located in 8 and 12 and modifing the pointer parameter by another value.
这篇关于StructLayout 和 FieldOffset 的未定义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文