Reputation: 59
the following is in a c# code (the whole project is too large) with a new format which I have never seen before, I don't know how FieldOffset could be placed before the variable definition! I am trying to use this struct to assign a float value=55 to Field2Float, then I surprisingly find Field2Int is also automatically assigned with a value 1113325568, how does this happen? since I am translating this code to python, how should I do the same thing in python? thanks
public class LutG1Record
{
/// <summary>Instruction value.</summary>
[FieldOffset(0)] public byte Instruction;
/// <summary>First field value split into 3 bytes.</summary>
[FieldOffset(1)] private byte field1b0;
[FieldOffset(2)] private byte field1b1;
[FieldOffset(3)] private byte field1b2;
/// <summary>Instruction combined with Field1 in a 32-bit int.</summary>
[FieldOffset(0)] private int InstructionAndField1;
/// <summary>Second field value is an integer (use Field2Float to store a float).</summary>
[FieldOffset(4)] public int Field2Int;
/// <summary>Second field value is a float (use Field2Int to store an int).</summary>
[FieldOffset(4)] public float Field2Float;
/// <summary>
/// This represents a 24 bit uint field.
/// </summary>
update: for float value = 55.0, if i use
var bytes = BitConverter.GetBytes(record.Field2Float);
var result = string.Format("0x{0:x}{1:x}{2:x}{3:x}", bytes[0], bytes[1], bytes[2], bytes[3]);
I could get result = 0x005c42
then for another value 1113325568 it is 425c0000
so looks both Field2Float and Field2Int just read the same location value?
Upvotes: 0
Views: 66
Reputation: 67380
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.
Upvotes: 1