4
Vote

POSTPONED: Add FieldOffsetAttribute

description

Structs has a LayoutKindAttribute which allows the individual fields of a struct to be accessed in memory a certain way.
 
The Explicit LayoutKind is useless without the FieldOffsetAttribute to put a field at a certain location in memory.

comments

wrote Mar 3, 2011 at 8:25 PM

I will investigate

wrote Mar 7, 2011 at 10:09 PM

we will not fix this one

lorenzte wrote Jul 5, 2011 at 7:09 AM

** Closed by lorenzte 3/7/2011 3:09 PM

juliusfriedman wrote Jul 5, 2011 at 7:09 AM

Can you explain what the use of LayoutKind attribute is in the .Net Micro Fx without this additional attribute? I have a few places this trick would come in handy and without the FieldOffset or unsafe code I am not sure how one would achieve use of this attribute.

aalmada wrote Apr 20, 2012 at 10:01 AM

An example of its usefulness: marshalling a float (System.Single) or a double (System.double).

The methods InsertValueIntoArray and ExtractValueFromArray of Microsoft.SPOT.Hardware.Utility, convert a UInt32 to and from a byte array. The issue is, how to bit-wise cast a Single to a UInt32?

One way to do it is to use pointers but, what I read is that "unsafe" is not officially supported in .NET MF: http://forums.netduino.com/index.php?/topic/308-bitconverter/page__view__findpost__p__2151

I used the "union" method many times in regular .NET and it works very efficiently. Without the support of FieldOffestAttribute, it's not possible to use: http://forums.netduino.com/index.php?/topic/3130-struct-fieldoffset0-attribute-not-implemented/page__view__findpost__p__21834

If neither method is officialy supported, how can I do it?

juliusfriedman wrote Apr 20, 2012 at 11:45 AM

This would be really useful...

I believe with unsafe code we can utilize the TypedReference and do what we need to from there.

I also believe that using your own binary serialization through the use of the exposed IsLittleEndian property can allow you to do what you need to do albeit it gets to be a little more work than is desirable.

See
http://msdn.microsoft.com/en-us/library/ee436893.aspx

For an introduction to the TypedReference structure.

aalmada wrote Apr 20, 2012 at 1:26 PM

Thanks! I didn't know about TypedReference...
I tried the following:

public struct Test
{
public uint Value;
}

var test = new Test();
var info = test.GetType().GetField("Value");
var reference = __makeref(test);
info.SetValueDirect(reference, Single.MaxValue);

I'm sorry to say this but, it's still ridiculous. TypedReference and __makeref are supported but FieldInfo doesn't have the SetValueDirect method... :-(

juliusfriedman wrote Apr 20, 2012 at 1:41 PM

You can't win on earth :P