Marshal.SizeOf error in computing size

c#, marshalling, sizeof, structure

Solution

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;
}

Problem

i have a structure ``` public struct SERVER_USB_DEVICE { USB_HWID usbHWID; byte status; bool bExcludeDevice; bool bSharedManually; ulong ulDeviceId; ulong ulClientAddr; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] string usbDeviceDescr; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] string locationInfo; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] string nickName; } ``` i am getting following error System.ArgumentException was unhandled Message="Type 'SERVER_USB_DEVICE' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed." at following line ``` Marshal.SizeOf(typeof(USBOverNetWrapper.FT_SERVER_USB_DEVICE)); ``` what is wrong in the code? Abdul Khaliq

Original source