/// <summary> /// Convert MarshalAsAttribute data into CustomAttributeData form. Returns null if the core assembly cannot be loaded or if the necessary /// types aren't in the core assembly. /// </summary> public static CustomAttributeData?TryComputeMarshalAsCustomAttributeData(Func <MarshalAsAttribute> marshalAsAttributeComputer, MetadataLoadContext loader) { // Make sure all the necessary framework types exist in this MetadataLoadContext's core assembly. If one doesn't, skip. CoreTypes ct = loader.GetAllFoundCoreTypes(); if (ct[CoreType.String] == null || ct[CoreType.Boolean] == null || ct[CoreType.UnmanagedType] == null || ct[CoreType.VarEnum] == null || ct[CoreType.Type] == null || ct[CoreType.Int16] == null || ct[CoreType.Int32] == null) { return(null); } ConstructorInfo?ci = loader.TryGetMarshalAsCtor(); if (ci == null) { return(null); } Func <CustomAttributeArguments> argumentsPromise = () => { // The expensive work goes in here. It will not execute unless someone invokes the Constructor/NamedArguments properties on // the CustomAttributeData. MarshalAsAttribute ma = marshalAsAttributeComputer(); Type attributeType = ci.DeclaringType !; CustomAttributeTypedArgument[] cats = { new CustomAttributeTypedArgument(ct[CoreType.UnmanagedType] !, (int)(ma.Value)) };
public MarshalAsAttributeTest() { //create a dynamic assembly with the required attribute //and check for the validity dynAsmName.Name = "TestAssembly"; dynAssembly = Thread.GetDomain().DefineDynamicAssembly( dynAsmName, AssemblyBuilderAccess.Run ); // Set the required Attribute of the assembly. Type attribute = typeof(MarshalAsAttribute); ConstructorInfo ctrInfo = attribute.GetConstructor( new Type [] { typeof(UnmanagedType) } ); CustomAttributeBuilder attrBuilder = new CustomAttributeBuilder(ctrInfo, new object [1] { UnmanagedType.LPWStr }); dynAssembly.SetCustomAttribute(attrBuilder); object [] attributes = dynAssembly.GetCustomAttributes(true); attr = attributes [0] as MarshalAsAttribute; }
internal MarshalAsAttribute ToMarshalAsAttribute() { MarshalAsAttribute attr = new MarshalAsAttribute(t); attr.ArraySubType = tbase; attr.MarshalCookie = mcookie; attr.MarshalType = marshaltype; attr.MarshalTypeRef = marshaltyperef; if (count == -1) { attr.SizeConst = 0; } else { attr.SizeConst = count; } if (param_num == -1) { attr.SizeParamIndex = 0; } else { attr.SizeParamIndex = (short)param_num; } return(attr); }
private void AddInput(string str, string log) { Type structType = typeof(ConsoleInputEventStruct); FieldInfo strField = structType.GetField("Str"); object[] attributes = strField.GetCustomAttributes(typeof(MarshalAsAttribute), false); if (attributes.Length != 1) { throw _logger.WriteException(new InvalidOperationException("MarshalAs attribute not found for ConsoleInputEventStruct.Str")); } MarshalAsAttribute marshalAsAttribute = (MarshalAsAttribute)attributes[0]; if (marshalAsAttribute.SizeConst <= str.Length) { throw _logger.WriteException( new SessionLocalException( _session, string.Format(CultureInfo.CurrentCulture, "Input [{0}] is too long ({1} limit)", str, marshalAsAttribute.SizeConst))); } lock (_input) { _input.Add(str); _log.Add(log); _inputEvent.Set(); } }
public static void TestPseudoCustomAttributes() { MethodInfo m = typeof(ParametersWithPseudoCustomtAttributes).Project().GetTypeInfo().GetDeclaredMethod("Foo"); ParameterInfo[] pis = m.GetParameters(); { ParameterInfo p = pis[0]; CustomAttributeData cad = p.CustomAttributes.Single(c => c.AttributeType == typeof(InAttribute).Project()); InAttribute i = cad.UnprojectAndInstantiate <InAttribute>(); } { ParameterInfo p = pis[1]; CustomAttributeData cad = p.CustomAttributes.Single(c => c.AttributeType == typeof(OutAttribute).Project()); OutAttribute o = cad.UnprojectAndInstantiate <OutAttribute>(); } { ParameterInfo p = pis[2]; CustomAttributeData cad = p.CustomAttributes.Single(c => c.AttributeType == typeof(OptionalAttribute).Project()); OptionalAttribute o = cad.UnprojectAndInstantiate <OptionalAttribute>(); } { ParameterInfo p = pis[3]; CustomAttributeData cad = p.CustomAttributes.Single(c => c.AttributeType == typeof(MarshalAsAttribute).Project()); MarshalAsAttribute ma = cad.UnprojectAndInstantiate <MarshalAsAttribute>(); Assert.Equal(UnmanagedType.I4, ma.Value); } }
/// <summary> /// 根据结构体成员标注的特性对结构体值的字节数组进行字节翻转 /// </summary> private static byte[] RespectEndianness(byte[] bytes, Type type) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo field in fields) { if (field.IsDefined(typeof(EndianAttribute), false) && Marshal.SizeOf(field.FieldType) > 1) { EndianAttribute endianattr = (EndianAttribute)field.GetCustomAttributes(typeof(EndianAttribute), false)[0]; if ((endianattr.Endian == Endianness.BigEndian && BitConverter.IsLittleEndian) || (endianattr.Endian == Endianness.LittleEndian && !BitConverter.IsLittleEndian)) { int mag = 1; if (field.IsDefined(typeof(MarshalAsAttribute), false) && field.GetType().IsArray) { MarshalAsAttribute marshalattr = (MarshalAsAttribute)field.GetCustomAttributes(typeof(MarshalAsAttribute), false)[0]; mag = marshalattr.SizeConst > 1 ? marshalattr.SizeConst : 1; } for (int i = 0; i < mag; i++) { Array.Reverse(bytes, Marshal.OffsetOf(type, field.Name).ToInt32() + (i * Marshal.SizeOf(field.FieldType)), Marshal.SizeOf(field.FieldType)); } } } } return(bytes); }
internal MarshalAsAttribute ToMarshalAsAttribute() { MarshalAsAttribute marshalAsAttribute = new MarshalAsAttribute(this.t); marshalAsAttribute.ArraySubType = this.tbase; marshalAsAttribute.MarshalCookie = this.mcookie; marshalAsAttribute.MarshalType = this.marshaltype; marshalAsAttribute.MarshalTypeRef = this.marshaltyperef; if (this.count == -1) { marshalAsAttribute.SizeConst = 0; } else { marshalAsAttribute.SizeConst = this.count; } if (this.param_num == -1) { marshalAsAttribute.SizeParamIndex = 0; } else { marshalAsAttribute.SizeParamIndex = (short)this.param_num; } return(marshalAsAttribute); }
internal static bool CanSerializeValueType(Type type, bool strict) { if (type.IsGenericType) { return(false); } HashSet <FieldInfo> fields = new HashSet <FieldInfo>(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)); // adding private fields from base types while (type.BaseType != null) { type = type.BaseType; foreach (FieldInfo field in type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)) { if (!fields.Contains(field)) { fields.Add(field); } } } // checking fields foreach (FieldInfo field in fields) { if (field.FieldType.IsValueType) { if (field.FieldType.IsPrimitive) { continue; } if (!CanSerializeValueType(field.FieldType, strict)) { return(false); } } else if (field.FieldType.IsArray || field.FieldType == Reflector.StringType) { if (strict) { return(false); } object[] attrs = field.GetCustomAttributes(typeof(MarshalAsAttribute), false); MarshalAsAttribute marshalAs = attrs.Length > 0 ? attrs[0] as MarshalAsAttribute : null; if (marshalAs != null && (field.FieldType.IsArray && marshalAs.Value == UnmanagedType.ByValArray || field.FieldType == Reflector.StringType && marshalAs.Value == UnmanagedType.ByValTStr)) { continue; } return(false); } else { return(false); } } return(true); }
public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Initialize a instance of MarshalAsAttribute Class 4"); try { for (int i = 40; i <= 45; i++) { UnmanagedType unmanagedType = (UnmanagedType)i; #region Switch switch (unmanagedType) { case UnmanagedType.AsAny: MarshalAsAttribute myMarshalAsAttribute1 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute1 == null || myMarshalAsAttribute1.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("007.1", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute1.Value.ToString()); retVal = false; } break; case UnmanagedType.LPArray: MarshalAsAttribute myMarshalAsAttribute2 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute2 == null || myMarshalAsAttribute2.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("007.2", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute2.Value.ToString()); retVal = false; } break; case UnmanagedType.LPStruct: MarshalAsAttribute myMarshalAsAttribute3 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute3 == null || myMarshalAsAttribute3.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("007.3", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute3.Value.ToString()); retVal = false; } break; case UnmanagedType.Error: MarshalAsAttribute myMarshalAsAttribute5 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute5 == null || myMarshalAsAttribute5.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("007.4", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute5.Value.ToString()); retVal = false; } break; } #endregion } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e); retVal = false; } return(retVal); }
private static int stringLength(FieldInfo fld) { var attr = fld.GetCustomAttributes(typeof(MarshalAsAttribute), false); MarshalAsAttribute maa = (MarshalAsAttribute)attr[0]; var constSize = maa.SizeConst; return(constSize); }
internal static ParameterInfo New(Type type, MemberInfo member, MarshalAsAttribute marshalAs) { #if NET_4_0 return(new MonoParameterInfo(type, member, marshalAs)); #else return(new ParameterInfo(type, member, marshalAs)); #endif }
/// <summary> /// Fix endianness /// </summary> /// <typeparam name="DataType">Type of the struct to fix endianness for</typeparam> /// <param name="data">Struct bytes</param> /// <param name="startOffset">Field byte offset</param> private static void FixEndianness <DataType>(byte[] data, int startOffset = 0) where DataType : struct { List <FieldInfo> fields = typeof(DataType).GetFields().Where(field => !field.IsStatic && field.FieldType != typeof(string)).ToList(); if (!fields.Any()) { int size = Marshal.SizeOf(typeof(DataType)); Array.Reverse(data, startOffset, size); } foreach (FieldInfo field in fields) { Type fieldType = field.FieldType; int offset = Marshal.OffsetOf(typeof(DataType), field.Name).ToInt32() + startOffset; if (fieldType.IsEnum) { fieldType = Enum.GetUnderlyingType(fieldType); } else if (fieldType.IsArray) { MarshalAsAttribute attribute = field.GetCustomAttribute(typeof(MarshalAsAttribute)) as MarshalAsAttribute; fieldType = fieldType.GetElementType(); if (attribute != null) { int size = Marshal.SizeOf(fieldType); int count = attribute.SizeConst; for (int counter = 0; counter < count; counter++) { typeof(Powerslave) .GetMethod("FixEndianness", BindingFlags.NonPublic | BindingFlags.Static) .MakeGenericMethod(fieldType) .Invoke(null, new object[] { data, offset + (counter * size) }); } } } else { List <FieldInfo> sub = fieldType.GetFields().Where(subField => !subField.IsStatic && field.FieldType != typeof(string)).ToList(); if (sub.Any()) { typeof(Powerslave) .GetMethod("FixEndianness", BindingFlags.NonPublic | BindingFlags.Static) .MakeGenericMethod(fieldType) .Invoke(null, new object[] { data, offset }); } else { int size = Marshal.SizeOf(fieldType); Array.Reverse(data, offset, size); } } } }
private void CreateMarshalAttribue(FieldBuilder field, MarshalAsAttribute attrib) { List <object> attribValues = new List <object>(1); List <FieldInfo> attribFields = new List <FieldInfo>(1); attribValues.Add(attrib.SizeConst); attribFields.Add(attrib.GetType().GetField("SizeConst")); field.SetCustomAttribute(new CustomAttributeBuilder(marshalAsCtor, new object[] { attrib.Value }, attribFields.ToArray(), attribValues.ToArray())); }
public void CtorTest() { var a = new MarshalAsAttribute(UnmanagedType.Bool); Assert.AreEqual(UnmanagedType.Bool, a.Value); a = new MarshalAsAttribute((short)UnmanagedType.Bool); Assert.AreEqual(UnmanagedType.Bool, a.Value); }
internal RuntimeParameterInfo(Type type, MemberInfo member, MarshalAsAttribute marshalAs) { this.ClassImpl = type; this.MemberImpl = member; this.NameImpl = null; this.PositionImpl = -1; // since parameter positions are zero-based, return type pos is -1 this.AttrsImpl = ParameterAttributes.Retval; this.marshalAs = marshalAs; }
internal static Attribute[] GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType, out int count) { count = 0; bool flag = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); if (!flag && PseudoCustomAttribute.s_pca.GetValueOrDefault(caType) == null) { return(null); } Attribute[] array = new Attribute[PseudoCustomAttribute.s_pcasCount]; if (flag || caType == (RuntimeType)typeof(InAttribute)) { Attribute customAttribute = InAttribute.GetCustomAttribute(parameter); if (customAttribute != null) { Attribute[] array2 = array; int num = count; count = num + 1; array2[num] = customAttribute; } } if (flag || caType == (RuntimeType)typeof(OutAttribute)) { Attribute customAttribute = OutAttribute.GetCustomAttribute(parameter); if (customAttribute != null) { Attribute[] array3 = array; int num = count; count = num + 1; array3[num] = customAttribute; } } if (flag || caType == (RuntimeType)typeof(OptionalAttribute)) { Attribute customAttribute = OptionalAttribute.GetCustomAttribute(parameter); if (customAttribute != null) { Attribute[] array4 = array; int num = count; count = num + 1; array4[num] = customAttribute; } } if (flag || caType == (RuntimeType)typeof(MarshalAsAttribute)) { Attribute customAttribute = MarshalAsAttribute.GetCustomAttribute(parameter); if (customAttribute != null) { Attribute[] array5 = array; int num = count; count = num + 1; array5[num] = customAttribute; } } return(array); }
internal static bool IsDefined(RuntimeFieldInfo field, Type caType) { bool flag = (caType == typeof(object)) || (caType == typeof(Attribute)); if (!flag && (s_pca[caType] == null)) { return(false); } return(((flag || (caType == typeof(MarshalAsAttribute))) && MarshalAsAttribute.IsDefined(field)) || (((flag || (caType == typeof(FieldOffsetAttribute))) && FieldOffsetAttribute.IsDefined(field)) || ((flag || (caType == typeof(NonSerializedAttribute))) && NonSerializedAttribute.IsDefined(field)))); }
internal RuntimeParameterInfo(string name, Type type, int position, int attrs, object defaultValue, MemberInfo member, MarshalAsAttribute marshalAs) { NameImpl = name; ClassImpl = type; PositionImpl = position; AttrsImpl = (ParameterAttributes)attrs; DefaultValueImpl = defaultValue; MemberImpl = member; this.marshalAs = marshalAs; }
// Token: 0x0600441F RID: 17439 RVA: 0x000F9CF0 File Offset: 0x000F7EF0 private void Init(MarshalAsAttribute marshalAs) { Type typeFromHandle = typeof(MarshalAsAttribute); this.m_ctor = typeFromHandle.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]; this.m_typedCtorArgs = Array.AsReadOnly <CustomAttributeTypedArgument>(new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument(marshalAs.Value) }); int num = 3; if (marshalAs.MarshalType != null) { num++; } if (marshalAs.MarshalTypeRef != null) { num++; } if (marshalAs.MarshalCookie != null) { num++; } num++; num++; if (marshalAs.SafeArrayUserDefinedSubType != null) { num++; } CustomAttributeNamedArgument[] array = new CustomAttributeNamedArgument[num]; num = 0; array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("ArraySubType"), marshalAs.ArraySubType); array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("SizeParamIndex"), marshalAs.SizeParamIndex); array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("SizeConst"), marshalAs.SizeConst); array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("IidParameterIndex"), marshalAs.IidParameterIndex); array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("SafeArraySubType"), marshalAs.SafeArraySubType); if (marshalAs.MarshalType != null) { array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("MarshalType"), marshalAs.MarshalType); } if (marshalAs.MarshalTypeRef != null) { array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("MarshalTypeRef"), marshalAs.MarshalTypeRef); } if (marshalAs.MarshalCookie != null) { array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("MarshalCookie"), marshalAs.MarshalCookie); } if (marshalAs.SafeArrayUserDefinedSubType != null) { array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("SafeArrayUserDefinedSubType"), marshalAs.SafeArrayUserDefinedSubType); } this.m_namedArgs = Array.AsReadOnly <CustomAttributeNamedArgument>(array); }
public static void TestMarshalAsPseudoCustomAttribute(string fieldName, MarshalAsAttribute expected) { TypeInfo ecmaType = typeof(MarshalAsHolders).Project().GetTypeInfo(); FieldInfo ecmaField = ecmaType.GetDeclaredField(fieldName); Assert.NotNull(ecmaField); CustomAttributeData cad = ecmaField.CustomAttributes.Single(c => c.AttributeType.Name == nameof(MarshalAsAttribute)); MarshalAsAttribute actual = cad.UnprojectAndInstantiate <MarshalAsAttribute>(); AssertEqual(expected, actual); }
private int FieldSize(FieldInfo field) { if (field.FieldType.IsArray) { MarshalAsAttribute attr = (MarshalAsAttribute)field.GetCustomAttribute(typeof(MarshalAsAttribute), false); return(Marshal.SizeOf(field.FieldType.GetElementType()) * attr.SizeConst); } else { return(Marshal.SizeOf(field.FieldType)); } }
public object Parse(Type t, MarshalAsAttribute attri, string value) { object o = null; Type baseType = Type.GetType(t.FullName.Replace("&", "").Replace("[]", "")); if (baseType == null) { baseType = t.Assembly.GetType(t.FullName.Substring(0, t.FullName.IndexOf('['))); } if (t.Name.EndsWith("[][]") || t.Name.EndsWith("[,]")) { Type newType = Type.GetType(baseType.FullName + "[]"); string[] strs = value.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); Array array = Array.CreateInstance(baseType, strs.Length, strs[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Length); for (int i = 0; i < strs.Length; i++) { Array subArray = (Array)Parse(newType, attri, strs[i]); for (int j = 0; j < subArray.Length; j++) { array.SetValue(subArray.GetValue(j), i, j); } } o = array; } else if (t.Name.EndsWith("[]") || t.Name.EndsWith("&")) { string[] strs = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); Array array = null; if (t.Name.Equals("Array&")) { array = Array.CreateInstance(typeDic[attri.SafeArraySubType], strs.Length); for (int i = 0; i < strs.Length; i++) { array.SetValue(Parser.Instance.Parse(typeDic[attri.SafeArraySubType], attri, strs[i]), i); } } else { array = Array.CreateInstance(baseType, strs.Length); for (int i = 0; i < strs.Length; i++) { array.SetValue(Parser.Instance.Parse(baseType, attri, strs[i]), i); } } o = array; } else { } return(o); }
public void NullStringMarshalAsFields() { // Regression test for https://github.com/mono/mono/issues/12747 // // MarshalAsAttribute goes through // CustomAttributeBuilder.get_umarshal which tries to // build an UnmanagedMarshal value by decoding the CAB's data. // // The data decoding needs to handle null string (encoded as 0xFF) properly. var aName = new AssemblyName("Repro12747"); var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.RunAndSave, tempDir); var module = assembly.DefineDynamicModule(aName.Name, aName.Name + ".dll"); var prototypeMethodName = nameof(MethodForNullStringMarshalAsFields); var someMethod = this.GetType().GetMethod(prototypeMethodName, BindingFlags.Static | BindingFlags.NonPublic); var typeBuilder = module.DefineType("NewType" + module.ToString(), TypeAttributes.Class | TypeAttributes.Public); var methodBuilder = typeBuilder.DefineMethod("NewMethod", MethodAttributes.Public | MethodAttributes.HideBySig, typeof(void), new[] { typeof(string) }); var il = methodBuilder.GetILGenerator(); il.Emit(OpCodes.Ret); var param = someMethod.GetParameters()[0]; var paramBuilder = methodBuilder.DefineParameter(1, param.Attributes, null); MarshalAsAttribute attr = param.GetCustomAttribute <MarshalAsAttribute>(); var attrCtor = typeof(MarshalAsAttribute).GetConstructor(new[] { typeof(UnmanagedType) }); object[] attrCtorArgs = { attr.Value }; // copy over the fields from the real MarshalAsAttribute on the parameter of "MethodForNullStringMarshalAsFields", // including the ones that were initialized to null var srcFields = typeof(MarshalAsAttribute).GetFields(BindingFlags.Public | BindingFlags.Instance); var fieldArguments = new FieldInfo[srcFields.Length]; var fieldArgumentValues = new object[srcFields.Length]; for (int i = 0; i < srcFields.Length; i++) { var field = srcFields[i]; fieldArguments[i] = field; fieldArgumentValues[i] = field.GetValue(attr); } var attrBuilder = new CustomAttributeBuilder(attrCtor, attrCtorArgs, Array.Empty <PropertyInfo>(), Array.Empty <object>(), fieldArguments, fieldArgumentValues); // this encodes the CustomAttributeBuilder as a data // blob and then tries to decode it using // CustomAttributeBuilder.get_umarshal paramBuilder.SetCustomAttribute(attrBuilder); var finalType = typeBuilder.CreateType(); }
internal CustomAttributeData[]? GetPseudoCustomAttributesData() { int count = 0; if (IsNotSerialized) { count++; } if (DeclaringType !.IsExplicitLayout) { count++; } MarshalAsAttribute marshalAs = get_marshal_info(); if (marshalAs != null) { count++; } if (count == 0) { return(null); } CustomAttributeData[] attrsData = new CustomAttributeData[count]; count = 0; if (IsNotSerialized) { attrsData[count++] = new RuntimeCustomAttributeData((typeof(NonSerializedAttribute)).GetConstructor(Type.EmptyTypes) !); } if (DeclaringType.IsExplicitLayout) { var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument(typeof(int), GetFieldOffset()) }; attrsData[count++] = new RuntimeCustomAttributeData( (typeof(FieldOffsetAttribute)).GetConstructor(new[] { typeof(int) }) !, ctorArgs, Array.Empty <CustomAttributeNamedArgument>()); } if (marshalAs != null) { var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument(typeof(UnmanagedType), marshalAs.Value) }; attrsData[count++] = new RuntimeCustomAttributeData( (typeof(MarshalAsAttribute)).GetConstructor(new[] { typeof(UnmanagedType) }) !, ctorArgs, Array.Empty <CustomAttributeNamedArgument>());//FIXME Get named params } return(attrsData); }
public object Parse(Type t, MarshalAsAttribute attri, string value) { if (t == typeof(float) || t.Name.Equals(typeof(float).Name + "&", StringComparison.OrdinalIgnoreCase)) { return(float.Parse(value)); } if (t == typeof(double) || t.Name.Equals(typeof(double).Name + "&", StringComparison.OrdinalIgnoreCase)) { return(double.Parse(value)); } return(null); }
private static IEnumerable <T> changeStrings <T>(IEnumerable <T> array, FieldInfo[] fields) where T : struct { foreach (var info in fields) { if (info.FieldType == typeof(string)) { var attr = info.GetCustomAttributes(typeof(MarshalAsAttribute), false); MarshalAsAttribute maa = (MarshalAsAttribute)attr[0]; object value = info.GetValue(array); } } return(array); }
static bool buildMarshalAsAttribute(ParameterInfo source, ParameterBuilder destination, CustomAttributeData ca, byte?retValIndex) { MarshalAsAttribute maa = source.GetCustomAttribute <MarshalAsAttribute>(); if (maa.Value != UnmanagedType.LPArray) { // So far, we only mess with the arrays. return(false); } object[] ctorArgs = new object[1] { maa.Value }; Dictionary <FieldInfo, object> dictOld = ca.NamedArguments.Where(a => a.IsField) .ToDictionary(a => (FieldInfo)a.MemberInfo, a => a.TypedValue.Value); Dictionary <FieldInfo, object> dictNew = new Dictionary <FieldInfo, object>(); object obj = dictOld.valueOrDefault(fiSizeParamIndex); if (null != obj) { short idx = (short)obj; if (retValIndex.HasValue && retValIndex.Value <= idx) { // User has specified [RetValIndex], and the inserted retval parameter comes before the field user has specified in SizeParamIndex. // Combined with the native "this", need to increase the index by 2. idx += 2; } else { // Increment by 1 because the native "this" parameter. idx += 1; } dictNew[fiSizeParamIndex] = idx; } else if (dictOld.ContainsKey(fiSizeConst) && (int)dictOld[fiSizeConst] > 0) { dictNew[fiSizeConst] = dictOld[fiSizeConst]; } else { throw new ArgumentException("When marshaling arrays, you must specify either SizeParamIndex or SizeConst"); } var cab = new CustomAttributeBuilder(ciMarshalAs, ctorArgs, dictNew.Keys.ToArray(), dictNew.Values.ToArray()); destination.SetCustomAttribute(cab); return(true); }
public void FieldsTest() { var a = new MarshalAsAttribute(UnmanagedType.Bool); Assert.Null(a.MarshalCookie); Assert.Null(a.MarshalType); Assert.Null(a.MarshalTypeRef); Assert.Null(a.SafeArrayUserDefinedSubType); Assert.AreEqual((UnmanagedType)0, a.ArraySubType); Assert.AreEqual(VarEnum.VT_EMPTY, a.SafeArraySubType); Assert.AreEqual(0, a.SizeConst); Assert.AreEqual(0, a.IidParameterIndex); Assert.AreEqual(0, a.SizeParamIndex); }
private static void AssertEqual(MarshalAsAttribute m1, MarshalAsAttribute m2) { Assert.Equal(m1.ArraySubType, m2.ArraySubType); Assert.Equal(m1.IidParameterIndex, m2.IidParameterIndex); Assert.Equal(m1.MarshalCookie, m2.MarshalCookie); // The assembly identity of the serialized marshal type depends on which contracts the test assembly is built against. Assert.Equal(m1.MarshalType.RemoveAssemblyQualification(), m2.MarshalType.RemoveAssemblyQualification()); Assert.Equal(m1.MarshalTypeRef, m2.MarshalTypeRef); Assert.Equal(m1.SafeArraySubType, m2.SafeArraySubType); Assert.Equal(m1.SafeArrayUserDefinedSubType, m2.SafeArrayUserDefinedSubType); Assert.Equal(m1.SizeConst, m2.SizeConst); Assert.Equal(m1.SizeParamIndex, m2.SizeParamIndex); Assert.Equal(m1.Value, m2.Value); }
private void CreateMarshalAttribute(FieldBuilder field, MemberInfo member, MarshalAsAttribute attrib) { List <object> attribValues = new List <object>(2); List <FieldInfo> attribFields = new List <FieldInfo>(2); attribValues.Add(attrib.SizeConst); attribFields.Add(attrib.GetType().GetField("SizeConst")); //if (attrib.Value == UnmanagedType.ByValArray) //{ // attribValues.Add(attrib.ArraySubType); // attribFields.Add(attrib.GetType().GetField("ArraySubType")); //} field.SetCustomAttribute(new CustomAttributeBuilder(marshalAsCtor, new object[] { attrib.Value }, attribFields.ToArray(), attribValues.ToArray())); }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Return the property Value in MarshalAsAttribute class 2"); try { MarshalAsAttribute myMarshalAsAttribute = new MarshalAsAttribute(UnmanagedType.Currency); UnmanagedType myValue = myMarshalAsAttribute.Value; if (myValue != UnmanagedType.Currency) { TestLibrary.TestFramework.LogError("003", "the ExpectResult is " + UnmanagedType.Currency.ToString() +" but the ActualResult is " + myValue.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Return the field MarshalTypeRef in MarshalAsAttribute class 2"); try { MarshalAsAttribute myMarshalAsAttribute = new MarshalAsAttribute(UnmanagedType.Bool); Type myMarshalTypeRef = myMarshalAsAttribute.MarshalTypeRef; if (myMarshalTypeRef != null) { TestLibrary.TestFramework.LogError("003", "the ExpectResult is null but the ActualResult is " + myMarshalTypeRef.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Initialize a instance of MarshalAsAttribute Class 2"); try { short unmanagedType = Int16.MinValue; MarshalAsAttribute myMarshalAsAttribute = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute == null || myMarshalAsAttribute.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("003", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute.Value.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Return the field ArraySubType in MarshalAsAttribute class 2"); try { MarshalAsAttribute myMarshalAsAttribute = new MarshalAsAttribute(UnmanagedType.ByValArray| UnmanagedType.LPArray); UnmanagedType myVal = myMarshalAsAttribute.ArraySubType; if (myVal != 0) { TestLibrary.TestFramework.LogError("003", "the ExpectResult is 0 but the ActualResult is " + myVal.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Return the field SizeParamIndex in MarshalAsAttribute class 2"); try { MarshalAsAttribute myMarshalAsAttribute = new MarshalAsAttribute(UnmanagedType.Currency); short mySizeParamIndex = myMarshalAsAttribute.SizeParamIndex; if (mySizeParamIndex != 0) { TestLibrary.TestFramework.LogError("003", "the ExpectResult is 0 but the ActualResult is " + mySizeParamIndex); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Return the field MarshalCookie in MarshalAsAttribute class 1"); try { short unmanagedType = Int16.MaxValue; MarshalAsAttribute myMarshalAsAttribute = new MarshalAsAttribute(unmanagedType); string myMarshalCookie = myMarshalAsAttribute.MarshalCookie; if (myMarshalCookie != null) { TestLibrary.TestFramework.LogError("001", "the ExpectResult is null but the ActualResult is " + myMarshalCookie ); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Return the property Value in MarshalAsAttribute class 1"); try { short unmanagedType = Int16.MaxValue; MarshalAsAttribute myMarshalAsAttribute = new MarshalAsAttribute(unmanagedType); UnmanagedType myValue = myMarshalAsAttribute.Value; if (myValue != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("001", "the ExpectResult is "+ unmanagedType.ToString() +" but the ActualResult is " + myValue.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Return the field SizeParamIndex in MarshalAsAttribute class 1"); try { short unmanagedType = Int16.MaxValue; MarshalAsAttribute myMarshalAsAttribute = new MarshalAsAttribute(unmanagedType); short mySizeParamIndex = myMarshalAsAttribute.SizeParamIndex; if (mySizeParamIndex != 0) { TestLibrary.TestFramework.LogError("001", "the ExpectResult is 0 but the ActualResult is " + mySizeParamIndex); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Initialize a instance of MarshalAsAttribute Class 3"); try { for (int i = 25; i <= 38; i++) { UnmanagedType unmanagedType = (UnmanagedType)i; #region Switch switch (unmanagedType) { case UnmanagedType.IUnknown: MarshalAsAttribute myMarshalAsAttribute6 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute6 == null || myMarshalAsAttribute6.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("005.1", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute6.Value.ToString()); retVal = false; } break; case UnmanagedType.Struct: MarshalAsAttribute myMarshalAsAttribute8 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute8 == null || myMarshalAsAttribute8.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("005.3", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute8.Value.ToString()); retVal = false; } break; case UnmanagedType.ByValArray: MarshalAsAttribute myMarshalAsAttribute11 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute11 == null || myMarshalAsAttribute11.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("005.6", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute11.Value.ToString()); retVal = false; } break; case UnmanagedType.SysInt: MarshalAsAttribute myMarshalAsAttribute12 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute12 == null || myMarshalAsAttribute12.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("005.7", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute12.Value.ToString()); retVal = false; } break; case UnmanagedType.SysUInt: MarshalAsAttribute myMarshalAsAttribute13 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute13 == null || myMarshalAsAttribute13.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("005.8", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute13.Value.ToString()); retVal = false; } break; case UnmanagedType.FunctionPtr: MarshalAsAttribute myMarshalAsAttribute18 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute18 == null || myMarshalAsAttribute18.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("005.13", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute18.Value.ToString()); retVal = false; } break; } #endregion } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Initialize a instance of MarshalAsAttribute Class 4"); try { for (int i = 40; i <= 45; i++) { UnmanagedType unmanagedType = (UnmanagedType)i; #region Switch switch (unmanagedType) { case UnmanagedType.AsAny: MarshalAsAttribute myMarshalAsAttribute1 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute1 == null || myMarshalAsAttribute1.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("007.1", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute1.Value.ToString()); retVal = false; } break; case UnmanagedType.LPArray: MarshalAsAttribute myMarshalAsAttribute2 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute2 == null || myMarshalAsAttribute2.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("007.2", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute2.Value.ToString()); retVal = false; } break; case UnmanagedType.LPStruct: MarshalAsAttribute myMarshalAsAttribute3 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute3 == null || myMarshalAsAttribute3.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("007.3", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute3.Value.ToString()); retVal = false; } break; case UnmanagedType.Error: MarshalAsAttribute myMarshalAsAttribute5 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute5 == null || myMarshalAsAttribute5.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("007.4", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute5.Value.ToString()); retVal = false; } break; } #endregion } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Initialize a instance of MarshalAsAttribute Class 1"); try { for (int i = 2; i <= 12; i++) { UnmanagedType unmanagedType = (UnmanagedType)i; #region Switch switch (unmanagedType) { case UnmanagedType.Bool: MarshalAsAttribute myMarshalAsAttribute1 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute1 == null || myMarshalAsAttribute1.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("001.1", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute1.Value.ToString()); retVal = false; } break; case UnmanagedType.I1: MarshalAsAttribute myMarshalAsAttribute2 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute2 == null || myMarshalAsAttribute2.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("001.2", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute2.Value.ToString()); retVal = false; } break; case UnmanagedType.U1: MarshalAsAttribute myMarshalAsAttribute3 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute3 == null || myMarshalAsAttribute3.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("001.3", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute3.Value.ToString()); retVal = false; } break; case UnmanagedType.I2: MarshalAsAttribute myMarshalAsAttribute4 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute4 == null || myMarshalAsAttribute4.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("001.4", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute4.Value.ToString()); retVal = false; } break; case UnmanagedType.U2: MarshalAsAttribute myMarshalAsAttribute5 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute5 == null || myMarshalAsAttribute5.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("001.5", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute5.Value.ToString()); retVal = false; } break; case UnmanagedType.I4: MarshalAsAttribute myMarshalAsAttribute6 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute6 == null || myMarshalAsAttribute6.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("001.6", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute6.Value.ToString()); retVal = false; } break; case UnmanagedType.U4: MarshalAsAttribute myMarshalAsAttribute7 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute7 == null || myMarshalAsAttribute7.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("001.7", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute7.Value.ToString()); retVal = false; } break; case UnmanagedType.I8: MarshalAsAttribute myMarshalAsAttribute8 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute8 == null || myMarshalAsAttribute8.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("001.8", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute8.Value.ToString()); retVal = false; } break; case UnmanagedType.U8: MarshalAsAttribute myMarshalAsAttribute9 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute9 == null || myMarshalAsAttribute9.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("001.9", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute9.Value.ToString()); retVal = false; } break; case UnmanagedType.R4: MarshalAsAttribute myMarshalAsAttribute10 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute10 == null || myMarshalAsAttribute10.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("001.10", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute10.Value.ToString()); retVal = false; } break; case UnmanagedType.R8: MarshalAsAttribute myMarshalAsAttribute11 = new MarshalAsAttribute(unmanagedType); if (myMarshalAsAttribute11 == null || myMarshalAsAttribute11.Value != (UnmanagedType)unmanagedType) { TestLibrary.TestFramework.LogError("001.11", "the intance should not be null and its value ExpectResult is " + ((UnmanagedType)unmanagedType).ToString() + " but the ActualResult is " + myMarshalAsAttribute11.Value.ToString()); retVal = false; } break; } #endregion } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; }