2013-05-10 62 views
1

我試圖將一個結構從VB傳遞給C.將參數從VB.Net傳遞給C(結構體)

此結構只有2個成員。 問題是隻有第一個成員保持該值。

我想這是每個成員的大小問題,但我不知道如何解決。

實施例和代碼:

VB .NET代碼:

<DllImport("UserMode_C.dll")> _ 
Shared Sub someExample(ByVal handleOfSomething As IntPtr, ByRef Filter As __Structure) 
End Sub 

<StructLayout(LayoutKind.Sequential)> _ 
    Structure __Structure 
     <MarshalAs(UnmanagedType.U8)> Public UsbSerial As ULong 
     <MarshalAs(UnmanagedType.U8)> Public UsbType As ULong 
End Structure 

Dim Buffer As New __Structure 
Buffer.UsbSerial = 123456 
Buffer.UsbType = 8 

Device = 123456 

someExample(Device, Buffer) 

的C代碼:

typedef struct __Structure{ 
     ULONG UsbSerial; 
     ULONG UsbType; 
}__Structure, *__Structure; 

#define DllExport __declspec(dllexport) 


EXTERN_C 
{ 

     DllExport void someExample(HANDLE handleOfSomething, __Structure* Filter) 
     { 
      // 
      // Here we have 
      // Filter.UsbSerial = 123456 
      // Filter.UsbType = 0  <<<--- this is wrong! I sent 8. 
      /* ... */ 
     } 
} 
+1

它,當然,取決於所使用的編譯器,但傳統上是一個'long'用C是32位,但VB.NET中的「Long」是64位。改爲使用'UInteger'和'UnManagedType.U4'。 – 2013-05-10 12:06:08

+0

謝謝,工作! – lcssanches 2013-05-10 12:29:41

+0

@StevenDoggart @因爲修復了OP的問題,所以你應該讓它成爲答案,以便它可以被接受 – Mike 2013-05-10 12:32:14

回答

3

ULong的類型在VB.NET是一個64位(8字節)無符號整數。在窗口中,C中的ULONG類型是一個32位(4字節)無符號整數(VB.NET數據類型的一半大小)。

要解決它,只需改變你的結構,使用UInteger類型與UnManagedType.U4,像這樣:

<StructLayout(LayoutKind.Sequential)> 
Structure __Structure 
    <MarshalAs(UnmanagedType.U4)> Public UsbSerial As UInteger 
    <MarshalAs(UnmanagedType.U4)> Public UsbType As UInteger 
End Structure 
+0

不需要任何假設。 Windows上的['ULONG'](http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v = vs.85).aspx#ULONG)是'unsigned long',的確是4字節寬。 – 2013-05-10 12:39:09

+0

問題,即使在x64機器上也可以運行? – lcssanches 2013-05-10 13:10:50

+0

@DavidHeffernan謝謝你的澄清。我從未在窗口中使用過C語言。我以前很久以前在DOS下使用它,所以我不能100%確定它是什麼。我認爲走廊另一邊的一些專家,像你一樣,會說出來,並提供更權威的信息:)我已經更新了我的答案。 – 2013-05-10 13:12:49