I'm trying to get the field types of an unsafe struct using some fixed fields. The fixed fields FieldType do not return the actual type.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct MyStruct
{
public UInt32 Field1;
public fixed sbyte Field2[10];
public UInt64 Field3;
}
void Test()
{
var theStruct = new MyStruct();
string output = "";
foreach (FieldInfo fi in theStruct.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
{
output += fi.Name + ": " + fi.FieldType.ToString() + "\r\n";
}
}
Output:
Field1: System.UInt32
Field2: TestProjectNS.MyStruct+<Field2>e__FixedBuffer0
Field3: System.UInt64
I'm looking for Field2
to tell me it's sbyte
instead of TestProjectNS.MyStruct+<Field2>e__FixedBuffer0
C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
The Fixed Size Buffer's underlying type can be retrieved through the FixedBufferAttribute
, which is applied on the fixed size buffer statement.
foreach (FieldInfo fi in typeof(MyStruct).GetFields(BindingFlags.Public | BindingFlags.Instance))
{
var attr = fi.GetCustomAttributes(typeof(FixedBufferAttribute), false);
if(attr.Length > 0)
output += fi.Name + ": " + ((FixedBufferAttribute)attr[0]).ElementType + "\r\n";
else
output += fi.Name + ": " + fi.FieldType + "\r\n";
}
Or the single field short version:
var type = typeof (MyStruct)
.GetField("Field2")
.GetCustomAttributes(typeof (FixedBufferAttribute), false)
.Cast<FixedBufferAttribute>()
.Single()
.ElementType;
As CodeInChaos, I also needed to reflect it, but I do have the FixedBufferAttribute
:
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct MyStruct
{
public uint Field1;
[FixedBuffer(typeof(sbyte), 10)]
public <Field2>e__FixedBuffer0 Field2;
public ulong Field3;
// Nested Types
[StructLayout(LayoutKind.Sequential, Size=10), CompilerGenerated, UnsafeValueType]
public struct <Field2>e__FixedBuffer0
{
public sbyte FixedElementField;
}
}
Awesome question!
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