I wrote a little code snippet to demonstrate the issue.
The problem is that when I declare a struct with the Layout.Explicit
state,
it assigns an undefined value to the fields of that struct depending on the other value.
This issue only occurs when using the Layout.Explicit
state.
it is pretty hard to explain without code so here is a short sample.
using System.Runtime.InteropServices;
namespace ConsoleStruct
{
class Program
{
[StructLayout(LayoutKind.Explicit)]
struct TestStruct
{
[FieldOffset(0)]
public double dbl;
[FieldOffset(0)]
public ulong uu;
}
public static void SimpleMethod()
{
TestStruct st;
st.uu = 0;
st.dbl = 5000.0;
Console.WriteLine(st.uu.ToString()); // ==> uu becomes 4662219572839972864
//instead of 0 :(
// it looks like the value of uu is dependent on the
//value assigned to dbl
Console.ReadLine();
}
static void Main(string[] args)
{
SimpleMethod();
}
}
}
Can anybody please explain to me why this is happening. Using VS 2013. Thanks.
it looks like the value of uu is dependent on the value assigned to dbl
Yes it is. Because you gave them the same offsets, they occupy the same place in memory (inside the struct).
[FieldOffset(...)]
lets you layout the fields manually and you can make them overlap. Some unmanaged APIs require that.
Note that when you try overlap something with a reference field (like a string) you will get a runtime exception. Memory safety can only be upheld as long as you do this with value types only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With