diff --git a/S7.Net/S7.Net.csproj b/S7.Net/S7.Net.csproj index a5643f5d..228d5677 100644 --- a/S7.Net/S7.Net.csproj +++ b/S7.Net/S7.Net.csproj @@ -1,7 +1,7 @@  - net452;net462;netstandard2.0;netstandard1.3;net5.0;net6.0;net7.0 + net452;net462;netstandard2.0;net5.0;net6.0;net7.0 true Properties\S7.Net.snk S7.Net.UnitTest diff --git a/S7.Net/Types/Struct.cs b/S7.Net/Types/Struct.cs index 136638ac..c2f08193 100644 --- a/S7.Net/Types/Struct.cs +++ b/S7.Net/Types/Struct.cs @@ -9,12 +9,12 @@ namespace S7.Net.Types /// public static class Struct { - /// - /// Gets the size of the struct in bytes. - /// - /// the type of the struct - /// the number of bytes - public static int GetStructSize(Type structType) + /// + /// Gets the size of the struct in bytes. + /// + /// the type of the struct + /// the number of bytes + public static int GetStructSize(Type structType) { double numBytes = 0.0; @@ -24,10 +24,15 @@ public static int GetStructSize(Type structType) #else .GetFields(); #endif - - foreach (var info in infos) + int count = 0; + foreach (var info in infos) { - switch (info.FieldType.Name) + count++; + var type = info.FieldType; + string name = info.FieldType.Name; + if (type.BaseType == typeof(System.Enum)) + name = Enum.GetUnderlyingType(type).Name; + switch (name) { case "Boolean": numBytes += 0.125; @@ -75,11 +80,15 @@ public static int GetStructSize(Type structType) break; default: numBytes += GetStructSize(info.FieldType); + if (count != infos.Count()) { + if(numBytes % 2 != 0) + numBytes++;//word align + } break; } } - return (int)numBytes; - } + return (int)Math.Ceiling(numBytes); //For example: 9 bool data, length = 1.125, but actually occupies 2 bytes + } /// /// Creates a struct of a specified type by an array of bytes. @@ -111,7 +120,11 @@ public static int GetStructSize(Type structType) foreach (var info in infos) { - switch (info.FieldType.Name) + var type = info.FieldType; + string name = info.FieldType.Name; + if (type.BaseType == typeof(System.Enum)) + name = Enum.GetUnderlyingType(type).Name; + switch (name) { case "Boolean": // get the value @@ -238,6 +251,8 @@ public static int GetStructSize(Type structType) Buffer.BlockCopy(bytes, (int)Math.Ceiling(numBytes), buffer, 0, buffer.Length); info.SetValue(structValue, FromBytes(info.FieldType, buffer)); numBytes += buffer.Length; + if(numBytes %2 != 0) //word align + numBytes++; break; } }