Question

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;
}
Was it helpful?

Solution

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.)

OTHER TIPS

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top