Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshal.SizeOf error in computing size

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

like image 257
Abdul Khaliq Avatar asked Dec 14 '22 02:12

Abdul Khaliq


2 Answers

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;
}
like image 104
Sam Harwell Avatar answered Dec 16 '22 17:12

Sam Harwell


[StructLayout(LayoutKind.Sequential, Pack = 1)]
     public struct SERVER_USB_DEVICE{
         ....
     }

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

like image 45
KV Prajapati Avatar answered Dec 16 '22 17:12

KV Prajapati