views:

633

answers:

2

Hi

Using C#, does anyone know how to get the MarshalAsAttribute's Sizeconst value in runtime ?

Eg. I would like to retrieve the value of 10.

[StructLayout[LayoutKind.Sequential, Pack=1]
Class StructureToMarshalFrom
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    public byte[] _value1;
}

Thanks in advance

+4  A: 

Yup, with reflection:

FieldInfo field = typeof(StructureToMarshalFrom).GetField("_value1");
object[] attributes = field.GetCustomAttributes(typeof(MarshalAsAttribute), false);
MarshalAsAttribute marshal = (MarshalAsAttribute) attributes[0];
int sizeConst = marshal.SizeConst;

(Untested, and obviously lacking rather a lot of error checking, but should work.)

Jon Skeet
Well done. Compiled first time. Thanks
MegaByte
A: 
var x = new StructureToMarshalFrom();
var fields = x.GetType().GetFields();

var att = (MarshalAsAttribute[])fields[0].GetCustomAttributes(typeof(MarshalAsAttribute), false);
if (att.Length > 0) {
    Console.WriteLine(att[0].SizeConst);
}
Dave Markle