111,120
社区成员
发帖
与我相关
我的任务
分享
public struct STRU_TEST
{
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 20, ArraySubType = UnmanagedType.I4)]
public int[] nData;
};
/*
* 以上这个结构体中的成员使用的时候似乎要先new
* STRU_TEST test = new STRU_TEST();
* test.nData = new int[20];
* for (int i = 0; i < test.nData.Length; ++i)
* test.nData[i] = i + 1;
*
* 我的问题是:能不能从结构体的定义中得到SizeConst = 20 的这个值,用于
* test.nData = new int[20], 替换这个20,用变量的形式。
* 我试了这样一句:test.nData = new int[test.nData.Length];
* 但是报错了!。。。
*/
public struct STRU_TEST
{
[MarshalAsAttribute(SizeConst = 20)]
public int[] nData;
}
public class MarshalAsAttribute : Attribute
{
public int SizeConst;
}
STRU_TEST stu = new STRU_TEST();
Type clsType = typeof(STRU_TEST);
FieldInfo f = clsType.GetField("nData");
MarshalAsAttribute ma = (MarshalAsAttribute)Attribute.GetCustomAttribute(f, typeof(MarshalAsAttribute));
MarshalAsAttribute对象就可以拿到SizeConst了
public struct STRU_TEST
{
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = DataLength , ArraySubType = UnmanagedType.I4)]
public int[] nData;
public const int DataLength = 20; //<--
};
STRU_TEST stu_test = new STRU_TEST();
Type t = stu_test.GetType();
foreach (FieldInfo fieldInfo in t.GetFields())
{
if(fieldInfo == null)
continue;
if ("nData".Equals(fieldInfo.Name))
{
IList<CustomAttributeData> list= fieldInfo.GetCustomAttributesData();
if (list == null || list.Count < 1)
continue;
foreach (CustomAttributeData attData in list)
{
IList<CustomAttributeNamedArgument> customArgs = attData.NamedArguments;
if (customArgs == null) continue;
foreach (CustomAttributeNamedArgument customArg in customArgs)
{
if (customArg == null)
continue;
Console.WriteLine("{0}:{1}", customArg.MemberName, customArg.TypedValue.Value);
}
}
}
}