传递给系统调用的数据区域太小。 (异常来自 HRESULT:0x8007007A)

在做结构体向字节数组转换的时候,常遇到"传递给系统调用的数据区域太小"的错误,究其原因是因为英文与汉字的编码方式不同,一个汉字等于两个字节,而一个英文字母等于1个字节。所以,对于如下的结构体:

/// <summary>
    /// 报警协议数据区结构
    /// </summary>
    [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
    public struct DataAreaForAlarmAsk
    {
        /// char[20]
        [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 20)]
        public char[] szAlarmNo;
 
        /// char[10]
        [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 10)]
        public char[] szUserNo;
 
        /// char[100]
        [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 100)]
        public string szUserName;

。。。}
  对于szUserName,用户姓名,在国内的系统中,极可能就含有中文字母,那么我们获取时,务必将字符串长度折半,即50,具体如下
//用户名称
                alarmProtoAlarmAsk.dataAreaForAsk.szUserName = (alarm_user_name.Length < 50) ? alarm_user_name : alarm_user_name.Substring(0, 50);
				

原文地址:https://www.cnblogs.com/Robert-huge/p/5130284.html