S7NetPlus / s7netplus

S7.NET+ -- A .NET library to connect to Siemens Step7 devices
MIT License
1.32k stars 586 forks source link

WriteStruct gives an error "Index was outside the bounds of the array" #472

Open jminns23 opened 1 year ago

jminns23 commented 1 year ago

with this structure:

struct myData
{
    public short MyShortValue;
    public bool MyBoolean;
}

the number of bytes returned by the function Struct.GetStructSize would be 2.125 bytes which is returned as an integer with

return (int)numBytes;

The result is 2 bytes which provokes the error with the array bounds when sending the structure I think the number of bytes returned by the function should be return Math.Ceiling(numBytes);

As a workaround add fake booleans until a whole byte is occupied

gfoidl commented 1 year ago

It's this code https://github.com/S7NetPlus/s7netplus/blob/6aa0133081048131aa269d0d5b780ec7fe01028f/S7.Net/Types/Struct.cs#L32-L33

I assume the 0.125 comes from using booleans only as bit-field, so there must be 8 of them to be valid (as your workaround suggests).

Another workaround is to use byte instead of bool. And if the semantics of a bool are needed, you can create an instance method / property for that, e.g.:

struct myData
{
    public short MyShortValue;
    public byte MyBoolean;

    public bool MyBoolValue => MyBoolean > 0;
}

Note: even the struct is only meant for plain data, it still can have methods, properties.