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
When
MarshalAsAttribute.Value
is set toByValArray
, theSizeConst
must be set to indicate the number of elements in the array. TheArraySubType
field can optionally contain theUnmanagedType
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 withByValTStr
is determined by theSystem.Runtime.InteropServices.CharSet
argument of theSystem.Runtime.InteropServices.StructLayoutAttribute
applied to the containing structure. Always use theMarshalAsAttribute.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With