Marshal.SizeOf error in computing size

别说谁变了你拦得住时间么 提交于 2019-12-04 13:59:08

When MarshalAsAttribute.Value is set to ByValArray, the SizeConst must be set to indicate the number of elements in the array. The ArraySubType field can optionally contain the UnmanagedType of the array elements when it is necessary to differentiate among string types.

However I recommend you use this one instead:

ByValTStr: Used for in-line, fixed-length character arrays that appear within a structure. The character type used with ByValTStr is determined by the System.Runtime.InteropServices.CharSet argument of the System.Runtime.InteropServices.StructLayoutAttribute applied to the containing structure. Always use the MarshalAsAttribute.SizeConst field to indicate the size of the array.

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
// OR [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SERVER_USB_DEVICE
{
    USB_HWID usbHWID;
    byte status;
    bool bExcludeDevice;
    bool bSharedManually;
    ulong ulDeviceId;
    ulong ulClientAddr;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
    string usbDeviceDescr;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
    string locationInfo;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
    string nickName;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
     public struct SERVER_USB_DEVICE{
         ....
     }

http://msdn.microsoft.com/en-us/library/5s4920fa.aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!