Marshal.SizeOf计算大小错误 [英] Marshal.SizeOf error in computing size

查看:811
本文介绍了Marshal.SizeOf计算大小错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构

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

我遇到以下错误

System.ArgumentException未处理 Message =类型"SERVER_USB_DEVICE" 不能封送为不受管理的人 结构体;没有有意义的尺寸或 偏移量可以计算出来."

System.ArgumentException was unhandled Message="Type 'SERVER_USB_DEVICE' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed."

在下一行

Marshal.SizeOf(typeof(USBOverNetWrapper.FT_SERVER_USB_DEVICE));

代码有什么问题?

阿卜杜勒·哈利克(Abdul Khaliq)

Abdul Khaliq

推荐答案

MarshalAsAttribute.Value设置为ByValArray时,必须设置SizeConst来指示数组中的元素数. 当需要区分字符串类型时,ArraySubType字段可以选择包含数组元素的UnmanagedType.

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 :用于出现在结构内的嵌入式定长字符数组.与ByValTStr一起使用的字符类型由应用于包含结构的System.Runtime.InteropServices.StructLayoutAttributeSystem.Runtime.InteropServices.CharSet自变量确定.始终使用MarshalAsAttribute.SizeConst字段指示数组的大小.

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

这篇关于Marshal.SizeOf计算大小错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆