[ACCEPTED]-C# StructLayout.Explicit Question-structlayout
The common language runtime contains a verifier 15 that makes sure the running code (verifiable 14 IL) cannot possibly corrupt memory in the 13 managed environment. This prevents you to 12 declare such a structure in which fields 11 overlap. Basically, your struct contains 10 two data members. One integer (which is 9 4 bytes) and a native integer (pointer size). On 8 a 32 bit CLR, in which you are probably 7 running your code, the char[]
will take 4 bytes 6 so if you put the integer less than four 5 bytes away from the beginning of the struct, you'll 4 have overlapping fields. It's interesting 3 to note that both of your code snippets 2 with fail on a 64 bit runtime, as the pointer 1 size is 8 bytes.
I figured I'd respond with the solution 5 I used to create the union -- which was 4 my original intention. I used an unsafe 3 struct and a fixed array and then used a 2 property to interact with the fixed array. I 1 believe this should do what I want.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace StructTest
{
[StructLayout(LayoutKind.Explicit)]
unsafe struct OuterType
{
private const int BUFFER_SIZE = 100;
[FieldOffset(0)]
private int transactionType;
[FieldOffset(0)]
private fixed byte writeBuffer[BUFFER_SIZE];
public int TransactionType
{
get { return transactionType; }
set { transactionType = value; }
}
public char[] WriteBuffer
{
set
{
char[] newBuffer = value;
fixed (byte* b = writeBuffer)
{
byte* bptr = b;
for (int i = 0; i < newBuffer.Length; i++)
{
*bptr++ = (byte) newBuffer[i];
}
}
}
get
{
char[] newBuffer = new char[BUFFER_SIZE];
fixed (byte* b = writeBuffer)
{
byte* bptr = b;
for (int i = 0; i < newBuffer.Length; i++)
{
newBuffer[i] = (char) *bptr++;
}
}
return newBuffer;
}
}
}
class Program
{
static void Main(string[] args)
{
OuterType t = new OuterType();
System.Console.WriteLine(t);
}
}
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.