MarshalAsAttribute Sizeconst .NET
-
03-07-2019 - |
質問
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);
}
所属していません StackOverflow