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 - determine the storage needs for a type | Microsoft Learn
CS0208 error : Compiler Error CS0208 | Microsoft Learn
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[].