将结构编组到指针 - 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:“尝试读取或写入受保护的内存。这通常表明其他内存已损坏。”

来自

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.