vb.Net Marshal 结构到指针 - Byte 可以,Byte() 不行

问题描述 投票:0回答:1

我正在尝试从结构中获取指针,将其传递给非托管 DLL。

如果我使用这个结构,奇怪的事情如下:

Structure message
    Public x As Byte
End Structure

并像这样构建指针:

 Dim mess As message = New message With {.X = &H33}
 Dim sizeOfHeader As Integer = 1

 Dim pHeader As IntPtr = Marshal.AllocHGlobal(sizeOfHeader)

 Marshal.StructureToPtr(mess, pHeader, True)

一切都很好 - 我可以将指针传递给我的非托管应用程序,并获取正确的信息。

但是,如果我使用此结构(使用字节数组 - 因为我需要多个字节 - 将来长度可变):

Structure message
    Public x As Byte()
End Structure

并像这样构建指针:

 Dim mess As message = New message With {.X = New Byte() {&H33}}
 Dim sizeOfHeader As Integer = 1

 Dim pHeader As IntPtr = Marshal.AllocHGlobal(sizeOfHeader)

 Marshal.StructureToPtr(mess, pHeader, True)

失败 - 非托管应用程序接收的数据是随机的(不是 0x33)

我在这里做错了什么?

提前致谢!

编辑:

有时我也会从

System.AccessViolationException: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
函数中得到
Marshal.StructureToPtr
。 此外,有时调试器只是以代码 0xc0000374 结束(似乎是 STATUS_HEAP_CORRUPTION),但没有其他信息。

vb.net pointers structure marshalling unmanaged
1个回答
0
投票

我认为当你使用

Byte()
时,你真正想要的是:

Marshal.StructureToPtr(mess.x(0), pHeader, True)
© www.soinside.com 2019 - 2024. All rights reserved.