Size of a structure

What function do I use to get the Size of a structure

You can use the sizeof(Type) C# operator. However, the target of your sizeof() operation has to be an unmanaged data type, or a struct made up of only unmanaged types. You can take sizeof(int) but not sizeof(string). Likewise, sizeof(Good) below will compile, whereas sizeof(Bad) will not compile because it contains a managed type.

Note that you must also go to the project’s properties page, under the ‘Build’ tab, and check the box marked ‘allow unsafe code’. This isn’t an unsafe operation, but because it requires computing the physical address of something, it requires the ‘allow unsafe’ flag during compilation.

Here’s an example…

    public struct Good
    {
        float bar;
        int baz;
    }

    public struct Bad
    {
        float bar;
        int baz;
        string quux;
    }

    int sz;
    unsafe
    {
        sz = sizeof(Good); // This will tell you the size of the struct 'Good'
        sz = sizeof(Bad);  // This won't compile
    }

See also:
sizeof : sizeof operator - C# reference | Microsoft Docs
CS0208 error : Compiler Error CS0208 | Microsoft Docs

it gives an error

0000099F sizeof – Not supported

What are you trying to accomplish?

“Not supported” - crud - looks like I steered you wrong then. I noticed that the System.Runtime.InteropServices.Marshal.SizeOf(typeof(Point)) method wasn’t in mscorlib for TinyCLR and wouldn’t compile, but that the sizeof() did compile fine. The provided code sample compiled fine but I didn’t run it on a board (and still haven’t) so maybe that opcode is missing from the interpreter.

Truth is though, calculating sizeof() for unmanaged types (int, char, byte, float, double, …) is a matter of adding up the fundamental sizes and following the packing/alignment rules depending on which structure packing you’ve selected.

Like Mike said, hard to be more helpful without more info.
But in my case, hard to be less helpful than I was by offering a bad answer. Sorry 'bout that.

I have a big structure and want to find its size to store it in the EEPROM

Can you use the json library to serialize it into BSON or JSON before storing it?

I am presuming that your struct does not contain any strings or arrays, as that means that the size of the struct is meaningless because it now contains references to managed types.

It’s either JSON/BSON or get out paper, pencil, and an adding machine.

[Side note: You can used “unsafe struct” with the “fixed” keyword to create inline arrays, but I’ve never tried that with TinyCLR. Strings and arrays are otherwise managed data and stored outside of the struct.]

You could also use the builtin serialization support: https://docs.ghielectronics.com/software/tinyclr/tutorials/serialization.html

I am assuming structs are serializable.

Easy to get the size of the serialized byte[].

2 Likes