2013-05-10 64 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