- Home /
platform dependencies using InteropServices.StructLayout Explicit
Hi devs, my code works perfectly fine, but I'm concerned whether this will break when being compiled to multiple platforms.
I have a 2D byte vector used as a lookup in a map, that I am doubling as an index for faster comparison in my path finding. My solution is to mark the v2b struct as explicit, letting a ushort index overlap the two bytes, so that setting either the index or the coordinates will update the others:
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)]
public struct v2b
{
[System.Runtime.InteropServices.FieldOffset(0)]
public ushort index;
[System.Runtime.InteropServices.FieldOffset(0)]
public byte x;
[System.Runtime.InteropServices.FieldOffset(1)]
public byte y;
}
Everything works as intended, there might be better solutions, but right now I would just like to know if anyone knows of any issues with explicit layouts on any platforms?
Thanks in advance.
/jannek
Just had a talk with one of the engine coders, and seems worst case would be differences in endians, though that will probably not happen, since it's c#. I would still love to hear if anyone has any additional knowledge of this :)
Answer by clancy1066 · Apr 13, 2020 at 10:17 PM
If I have a class A that has a member that is like yours
public class A : Monobehaviour
{
v2b myVal;
}
If I do:
A myA = Instantiate(<valid "A" instance));
myA.y = 1;
, when I Instantiate() an"A", the "MyA" structure is garbage(non-null) that the compiler nor runtime exception handlers catch. " myA.y = 1;" crashes Unity hard.
Not sure if this is the same thing you might be seeing. I made a separate ticket for it. I'll let you know if I get a solid answer
Uhm your code doesn't make much sense. Your class A does not have a field called "y". I used struct layout explicit in the past without any issues. I'm also not sure what you mean by
the "$$anonymous$$yA" structure is garbage
it's a struct that therefore either part of the memory of the containing class or allocated on the stack. So the struct itself can not be null or "garbage". It can not be garbage if you still have access to it.
To me it seems your description is missing important details on your case. Also it seems that you used your answer just to put your own question forward. You should have asked your own question and add more details. Also a code example that actually makes sense would help to follow what your issue might be. It would also help to know a bit more about the background (Unity version, scripting backend, target platform) since certain platforms have various restrictions
edit
I just found your question and it's a very different case than the one in question here. The short answer is yes, you can not have reference types and value types share the same memory space. Last time I tried this the compiler complained about that. This is also verified through other peoples over here.