confusion in c class variables

I don’t know how FieldOffset could be placed before the variable definition!

FieldOffset is an attribute, and the full name of the class is FieldOffsetAttribute. This specific attribute can be placed before (or “on”) fields.

how does this happen?

This specific attribute instructs the compiler to generate the fields “on top of each other”, so Field2Int and Field2Float resolve to the same memory locations, with the same size (both int and float have the same size).

Though you’re missing the important second half of these kinds of declarations, using a struct and declaring it with StructLayout, otherwise the compiler is still more or less free to mangle your class definition up.

A quick Google search shows struct.pack can be used to convert float to int and back byte-wise in Python, which is what this sample is doing. By the way, this is not the only way to do this in C#, you can simply reinterpret a pointer to int* into a pointer to float* and then dereference it, much like in C.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top