gpt4 book ai didi

.net - 将参数从 VB .Net 传递到 C(结构)

转载 作者:太空宇宙 更新时间:2023-11-04 02:09:18 25 4
gpt4 key购买 nike

我正在尝试将一个结构从 VB 传递到 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.
/* ... */
}
}

最佳答案

VB.NET 中的 ULong 类型是一个 64 位(8 字节)无符号整数。在 Windows 上,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

关于.net - 将参数从 VB .Net 传递到 C(结构),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16481622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com