如何在RSLogix 5000的SCL中获取BOOL[]数组长度
Got it, I totally get where you're coming from—being able to dynamically grab array sizes at runtime is a game-changer for code reusability, instead of hardcoding constants every time. The SIZE() function works great for most data types like SINT[], INT[], DINT[], REAL[], structs, and strings, but it's super frustrating that it doesn't play nice with BOOL[] arrays. That's because Rockwell stores boolean arrays as bit-packed structures under the hood, which the SIZE() function isn't built to handle directly.
Here are a couple of reliable workarounds to get the runtime size of a BOOL[] array in SCL:
1. Calculate Using Total Byte Size
Since BOOL arrays pack 8 elements into a single byte, you can use the SIZEOF() function to get the total number of bytes the array occupies, then multiply by 8 to get the total count of BOOL elements. This works perfectly for fixed-size BOOL arrays.
Example code:
VAR MyBoolArray : BOOL[100]; // Your target BOOL array ArrayByteCount : DINT; BoolElementCount : DINT; END_VAR ArrayByteCount := SIZEOF(MyBoolArray); BoolElementCount := ArrayByteCount * 8;
2. Wrapped Struct for Reusable Length Tracking
If you want cleaner, more maintainable code, wrap your BOOL array in a struct that includes an explicit length constant. This way, you only define the array size once, and can reference the length value anywhere in your program without recalculations.
Example struct definition:
TYPE BoolArrayWithMetadata : STRUCT ElementCount : DINT := 100; // Define your array length here once Elements : BOOL[100]; // Match the length to the array size END_STRUCT END_TYPE
Then use it in your program:
VAR MyManagedBoolArray : BoolArrayWithMetadata; END_VAR // Access the length at runtime like this MyManagedBoolArray.ElementCount;
3. Use UpperBound Attribute (Firmware v30+)
If you're running CompactLogix firmware version 30 or newer, you can leverage the built-in array attribute UpperBound to get the highest index of the array. Since SCL arrays are 0-indexed, just add 1 to this value to get the total number of elements. This is the cleanest method if your hardware supports it.
Example code:
VAR MyBoolArray : BOOL[100]; BoolElementCount : DINT; END_VAR BoolElementCount := MyBoolArray.UpperBound + 1;
Quick Note on Why SIZE() Fails for BOOL[]
To clarify the root issue: The SIZE() function is designed for arrays where each element takes up a full byte or word of memory. Since BOOL arrays cram 8 bits (elements) into one byte, the function can't directly return the number of individual elements like it does for other data types. That's why SIZEOF() (which returns total byte size) combined with a multiplier, or the newer UpperBound attribute, are your best bets.
内容的提问来源于stack exchange,提问作者KasparJohannes

