C#を使用して、実行時にMarshalAsAttributeのSizeconst値を取得する方法を知っている人はいますか?
例えば。10の値を取得したいと思います。
[StructLayout[LayoutKind.Sequential, Pack=1]
Class StructureToMarshalFrom
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public byte[] _value1;
}
C#を使用して、実行時にMarshalAsAttributeのSizeconst値を取得する方法を知っている人はいますか?
例えば。10の値を取得したいと思います。
[StructLayout[LayoutKind.Sequential, Pack=1]
Class StructureToMarshalFrom
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public byte[] _value1;
}
うん、反省あり:
FieldInfo field = typeof(StructureToMarshalFrom).GetField("_value1");
object[] attributes = field.GetCustomAttributes(typeof(MarshalAsAttribute), false);
MarshalAsAttribute marshal = (MarshalAsAttribute) attributes[0];
int sizeConst = marshal.SizeConst;
(テストされておらず、明らかに多くのエラーチェックが不足していますが、機能するはずです。)
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);
}