I created a custom structure for processing RGBA values ββthat will be bound to the GPU.
In my type, I hold the individual components R, G, B, and A as byte values ββand overlap an unsigned 32-bit integer (Uint32) to easily transfer and assign a packed value. I know the concept is obvious, but here is a sample structure for a good measure:
[StructLayout(LayoutKind.Explicit, Size = 4)] public struct RGBA { [FieldOffset(0)] public uint32 PackedValue; [FieldOffset(0)] public byte R; [FieldOffset(1)] public byte G; [FieldOffset(2)] public byte B; [FieldOffset(3)] public byte A; }
Due to the way C # handles structures, each field must be explicitly specified in any constructor. In my case, this means that I have to assign values ββtwice in any constructors due to overlapping fields.
I could use:
public RGBA(uint packed value) { R = G = B = A = 0;
or I could first call the base constructor for each constructor as follows:
public RGBA(uint packedValue) : this() { PackedValue = packedValue; } public RGBA(byte r, byte g, byte b, byte a) : this() { R = r; G = g; B = b; A = a; }
Since this is used for graphical code, performance is critical, and I'm trying to find the most optimal way to handle building in this scenario. Using the first example seems to be the least cost of the two examples, because although it involves assigning all fields twice (once for PackedValue and once for fields R, G, B, and A), another example involves assigning all values ββ3 times (twice in default constructor and once in a specific constructor).
Is there a way to make the compiler recognize that these fields overlap and does not require the direct assignment of R, G, B, and A if PackedValue is assigned and vice versa? I suppose this can be done by manually setting up IL, but I'm wondering if there is a way to handle this more optimally directly in C #.
Any ideas?
constructor c # memory data-structures
Mike johnson
source share