2017-08-23 96 views
3

我嘗試將這些VB6類型轉換爲VB.NET世界。將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,所以我用編組站但Marshal.SizeOf(MyCD)返回錯誤值(12)如果我不使用互操作規模,並韋爾普,與StructureToPtr所有attemps結束錯誤。下面

的代碼,如果任何使用的理解:

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()) 
+0

對於記錄,VB6的'Long'通常映射到'Integer',而不是'UInteger'(除非DLL需要UInts,就是這樣)。 –

回答

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 

(該鏈路還包括幾個在結構便利功能,這我在這裏省略)

+0

啊! 'MashalAs SizeConst'是訣竅。順便說一句,在鏈接的討論是一個很好的發現,謝謝! –