将带有数组的VB6类型转换为VB.NET结构体

3

我试图将那些VB6类型转换为VB.NET世界。

Type TRACK_DATA
   Dim reserved As Byte
   Dim Control As Byte
   Dim Tracknumber As Byte
   Dim reserved1 As Byte
   Dim address As Long
End Type

Type CDTOC
  Dim Length As Long
  Dim FirstTrack As Byte
  Dim LastTrack As Byte
  Dim Tracks(100) As TRACK_DATA
End Type

当前尝试惨败了

<System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size:=8)>
Structure TRACK_DATA
    Public reserved As Byte
    Public Control As Byte
    Public Tracknumber As Byte
    Public reserved1 As Byte
    Public address As UInteger
End Structure

<System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size:=806)>
Structure CDROM_TOC '4 + 1 + 1 + 800 = 806
    Public Length As UInteger
    Public FirstTrack As Byte
    Public LastTrack As Byte
    Public Tracks() As TRACK_DATA 
End Structure
...
Dim MyCD As CDTOC
ReDim MyCD.Tracks(100)

你有什么提示怎么做呢?

需要传递参数并将它们传回外部dll,所以我使用了Marshalling,但是Marshal.SizeOf(MyCD)如果不使用InterOp Size会返回错误的值(12),而且,所有尝试使用StructureToPtr都失败了。

下面是代码,如果有用的话:

    Toc_len = Marshal.SizeOf(MyCD)
    Dim Toc_ptr As IntPtr = Marshal.AllocHGlobal(CInt(Toc_len))

    'open the drive
    ...

    'access to the TOC
    DeviceIoControl(hFile, IOCTL_CDROM_READ_TOC, IntPtr.Zero, 0, Toc_ptr, Toc_len, BytesRead, IntPtr.Zero)

    'copy back the datas from unmanaged memory
    'fails here !
    MyCD = Marshal.PtrToStructure(Toc_ptr, CDTOC.GetType())

记录一下,VB6中的Long通常被映射为Integer,而不是UInteger(除非DLL需要UInts)。 - Visual Vincent
1个回答

9
这里有一些非常广泛的讨论(包括示例代码)链接如下:https://social.msdn.microsoft.com/Forums/en-US/3df9e61d-440f-4bea-9556-b2531b30e5e6/problem-with-deviceiocontrol-function?forum=vblanguage 您的结构只是缺少Tracks成员上的属性,以告诉编译器它是一个内联的100个元素的数组。
来自链接的内容:
<StructLayout(LayoutKind.Sequential)> _
Structure CDROM_TOC
    Public Length As UShort
    Public FirstTrack As Byte
    Public LastTrack As Byte
    <MarshalAs(UnmanagedType.ByValArray, SizeConst:=100)> _
    Public TrackData() As TRACK_DATA
End Structure

(链接中还包括一些在此处被省略的结构中的便利函数。)

啊!MashalAs SizeConst就是诀窍。顺便说一下,链接中的讨论是一个很好的发现,谢谢! - Proger_Cbsk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接