/// <summary> /// Add MarshalAs attribute /// </summary> /// <param name="xmlField"></param> /// <param name="fieldBuilder"></param> private void CreateRTMarshalAsAttribute(XmlStructFieldLayout xmlField, FieldBuilder fieldBuilder) { // Find MarshalAsAttribute's constructor by signature, then invoke var ctorParameters = new Type[] { typeof(UnmanagedType) }; var ctorInfo = typeof(MarshalAsAttribute).GetConstructor(ctorParameters); var fields = typeof(MarshalAsAttribute).GetFields(BindingFlags.Public | BindingFlags.Instance); var sizeConst = (from f in fields where f.Name == "SizeConst" select f).ToArray(); var marshalAsAttr = new CustomAttributeBuilder(ctorInfo, new object[] { xmlField.MarshalAsUnmanagedType }, sizeConst, new object[] { xmlField.MarshalAsSizeConst }); fieldBuilder.SetCustomAttribute(marshalAsAttr); }
/// <summary> /// Add Metadata attribute /// </summary> /// <param name="xmlField"></param> /// <param name="fieldBuilder"></param> private void CreateRTMetadataAttribute(XmlStructFieldLayout xmlField, FieldBuilder fieldBuilder) { // Find MarshalAsAttribute's constructor by signature, then invoke var metadataType = typeof(MetadataHelpAttribute); var ctorInfo = metadataType.GetConstructor(Type.EmptyTypes); List<PropertyInfo> lstPropInfo = new List<PropertyInfo>(); List<object> lstPropValues = new List<object>(); if(string.IsNullOrEmpty(xmlField.Metadata.Description) == false) { lstPropInfo.Add(metadataType.GetProperty("Description")); lstPropValues.Add(xmlField.Metadata.Description); } if (string.IsNullOrEmpty(xmlField.Metadata.DisplayName) == false) { lstPropInfo.Add(metadataType.GetProperty("DisplayName")); lstPropValues.Add(xmlField.Metadata.DisplayName); } var fields = metadataType.GetFields(BindingFlags.Public | BindingFlags.Instance); var marshalAsAttr = new CustomAttributeBuilder(ctorInfo, new object[] { }, lstPropInfo.ToArray(), lstPropValues.ToArray()); fieldBuilder.SetCustomAttribute(marshalAsAttr); }
/// <summary> /// Create field /// </summary> /// <param name="typeBuilder"></param> /// <param name="xmlStruct"></param> /// <param name="xmlField"></param> /// <returns></returns> private FieldBuilder CreateRTFieldType(TypeBuilder typeBuilder, XmlStructLayoutRoot xmlStruct, XmlStructFieldLayout xmlField) { Type fieldType = null; if (xmlField.NetType != TypeCode.Empty) fieldType = FactoryStandardType.Get(xmlField.NetType); if (string.IsNullOrEmpty(xmlField.RefType) == false) { // Find the type from current assembly fieldType = RTAssemblyBuilder.GetType(xmlField.RefType, true); } if (xmlField.IsArray) fieldType = fieldType.MakeArrayType(); FieldBuilder fieldBuilder = typeBuilder.DefineField( xmlField.Name, fieldType, FieldAttributes.Public); if (xmlField.CanMarshallAsStaticSize == true) { CreateRTMarshalAsAttribute(xmlField, fieldBuilder); } if(xmlField.Metadata != null) { CreateRTMetadataAttribute(xmlField, fieldBuilder); } return fieldBuilder; }