MarshalAsAttribute Sizeconst .NET
-
03-07-2019 - |
Pregunta
Usando C #, ¿alguien sabe cómo obtener el valor Sizeconst de MarshalAsAttribute en tiempo de ejecución?
Por ej. Me gustaría recuperar el valor de 10.
[StructLayout[LayoutKind.Sequential, Pack=1]
Class StructureToMarshalFrom
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public byte[] _value1;
}
Solución
Sí, con reflexión:
FieldInfo field = typeof(StructureToMarshalFrom).GetField("_value1");
object[] attributes = field.GetCustomAttributes(typeof(MarshalAsAttribute), false);
MarshalAsAttribute marshal = (MarshalAsAttribute) attributes[0];
int sizeConst = marshal.SizeConst;
(Sin probar, y obviamente carece de una gran cantidad de comprobación de errores, pero debería funcionar.)
Otros consejos
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);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow