/// <summary> /// Initializes a new instance of the <see cref="RuntimeParameter"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="position">The position.</param> /// <param name="attributes">The attributes.</param> public RuntimeParameter(string name, int position, ParameterAttributes attributes) { this.token = (HeapIndexToken)0; this.attributes = attributes; this.name = name; this.position = position; }
internal ParameterInfoMirror (MethodMirror method, int pos, TypeMirror type, string name, ParameterAttributes attrs) : base (method.VirtualMachine, 0) { this.method = method; this.pos = pos; this.type = type; this.name = name; this.attrs = attrs; }
public RoutineParameter(string name, SqlType type, ParameterDirection direction, ParameterAttributes attributes) { Attributes = attributes; Direction = direction; Type = type; Name = name; }
/******************* * * This is setting the parameter information * ********************/ /// <include file='doc\ConstructorBuilder.uex' path='docs/doc[@for="ConstructorBuilder.DefineParameter"]/*' /> public ParameterBuilder DefineParameter( int iSequence, ParameterAttributes attributes, String strParamName) // can be NULL string { return m_methodBuilder.DefineParameter(iSequence, attributes, strParamName); }
internal ParameterInfo (ParameterInfo pinfo, MemberInfo member) { this.ClassImpl = pinfo.ParameterType; this.MemberImpl = member; this.NameImpl = pinfo.Name; this.PositionImpl = pinfo.Position; this.AttrsImpl = pinfo.Attributes; //this.parent = pinfo; }
public ParameterStructure(string name, ParameterAttributes attr, TypeStructure pt, CilStructure def) { Name = name; Attributes = attr; ParamType = pt; DefaultValue = def; AppendChild(DefaultValue); }
private ParameterInfo(ParameterInfo accessor, MemberInfo member) { this.MemberImpl = member; this.NameImpl = accessor.Name; this.ClassImpl = accessor.ParameterType; this.PositionImpl = accessor.Position; this.AttrsImpl = accessor.Attributes; }
internal ParameterInfo(MethodInfo owner, string name, Type parameterType, int position) { this.MemberImpl = owner; this.NameImpl = name; this.ClassImpl = parameterType; this.PositionImpl = position; this.AttrsImpl = ParameterAttributes.None; }
internal ParameterBuilder(ModuleBuilder moduleBuilder, int sequence, ParameterAttributes attribs, string name) { this.moduleBuilder = moduleBuilder; this.flags = (short)attribs; this.sequence = (short)sequence; this.nameIndex = name == null ? 0 : moduleBuilder.Strings.Add(name); this.name = name; }
/* to build a ParameterInfo for the return type of a method */ internal ParameterInfo (Type type, MemberInfo member, UnmanagedMarshal marshalAs) { this.ClassImpl = type; this.MemberImpl = member; this.NameImpl = ""; this.PositionImpl = -1; // since parameter positions are zero-based, return type pos is -1 this.AttrsImpl = ParameterAttributes.Retval; this.marshalAs = marshalAs; }
internal ParameterBuilder(MethodBuilder methodBuilder, int sequence, ParameterAttributes attributes, string strParamName) { this.m_iPosition = sequence; this.m_strParamName = strParamName; this.m_methodBuilder = methodBuilder; this.m_strParamName = strParamName; this.m_attributes = attributes; this.m_pdToken = new ParameterToken(TypeBuilder.SetParamInfo(this.m_methodBuilder.GetModuleBuilder().GetNativeHandle(), this.m_methodBuilder.GetToken().Token, sequence, attributes, strParamName)); }
#pragma warning restore 169, 414 internal ParameterBuilder (MethodBase mb, int pos, ParameterAttributes attributes, string strParamName) { name = strParamName; position = pos; attrs = attributes; methodb = mb; if (mb is DynamicMethod) table_idx = 0; else table_idx = mb.get_next_table_index (this, 0x08, true); }
public ApiMethodBuilder Parameter(Type type, string name = "param", ParameterAttributes attributes = ParameterAttributes.None) { _parameters.Add(new ApiParameter { Type = type, Name = name, Attributes = attributes }); return this; }
public ApiMethodBuilder DefaultParameter(Type type, object defaultValue, string name = "param", ParameterAttributes attributes = ParameterAttributes.Optional | ParameterAttributes.HasDefault) { _parameters.Add(new ApiParameter { Type = type, Name = name, DefaultValue = defaultValue, Attributes = attributes }); return this; }
public StubParameterInfo(int position, Type/*!*/ type, ParameterAttributes attributes, string name) { Debug.Assert(type != null); #if !SILVERLIGHT this.ClassImpl = type; this.AttrsImpl = attributes; this.NameImpl = name; this.PositionImpl = position; #endif }
private ParameterInfo(ParameterInfo accessor, MemberInfo member) { this.MemberImpl = member; this.NameImpl = accessor.Name; this.m_nameIsCached = true; this.ClassImpl = accessor.ParameterType; this.PositionImpl = accessor.Position; this.AttrsImpl = accessor.Attributes; this.m_tkParamDef = System.Reflection.MetadataToken.IsNullToken(accessor.MetadataToken) ? 0x8000000 : accessor.MetadataToken; this.m_scope = accessor.m_scope; }
private ParameterInfo(Signature signature, MetadataImport scope, int tkParamDef, int position, ParameterAttributes attributes, MemberInfo member) { this.PositionImpl = position; this.MemberImpl = member; this.m_signature = signature; this.m_tkParamDef = System.Reflection.MetadataToken.IsNullToken(tkParamDef) ? 0x8000000 : tkParamDef; this.m_scope = scope; this.AttrsImpl = attributes; this.ClassImpl = null; this.NameImpl = null; }
internal ParameterInfo(MethodInfo owner, string name, RuntimeType parameterType, int position) { this.MemberImpl = owner; this.NameImpl = name; this.m_nameIsCached = true; this.m_noDefaultValue = true; this.ClassImpl = parameterType; this.PositionImpl = position; this.AttrsImpl = ParameterAttributes.None; this.m_tkParamDef = 0x8000000; this.m_scope = MetadataImport.EmptyImport; }
public RoutineParameter(string name, SqlType type, ParameterDirection direction, ParameterAttributes attributes) { if (String.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); if (type == null) throw new ArgumentNullException("type"); Attributes = attributes; Direction = direction; Type = type; Name = name; }
// There is a single constructor that is used to create a Parameter. This is // only called from native so it can be private. /// <include file='doc\ParameterInfo.uex' path='docs/doc[@for="ParameterInfo.ParameterInfo1"]/*' /> internal ParameterInfo(Type theClass, String name, int position, ParameterAttributes attributes) { ClassImpl = theClass; NameImpl = name; PositionImpl = position; AttrsImpl = attributes; DefaultValueImpl = DBNull.Value; MemberImpl = null; _importer = (IntPtr)0; _token = 0; }
private void CheckSupport(ParameterAttributes parameterAttributes) { string warningTemplate = "Parameter '" + name + "' has unsupported attribute: '{0}'."; // in order to reduce output we warn only about important attributes which are not currently // supported: // TODO: support this: if ((parameterAttributes & ParameterAttributes.HasDefault) != 0) { Logger.Warning(warningTemplate, "HasDefault"); } // TODO: support this: if ((parameterAttributes & ParameterAttributes.HasFieldMarshal) != 0) { Logger.Warning(warningTemplate, "HasFieldMarshal"); } // TODO: support this: if ((parameterAttributes & ParameterAttributes.Lcid) != 0) { Logger.Warning(warningTemplate, "Lcid"); } // TODO: support this: if ((parameterAttributes & ParameterAttributes.Optional) != 0) { Logger.Warning(warningTemplate, "Optional"); } // TODO: support this: if ((parameterAttributes & ParameterAttributes.Retval) != 0) { Logger.Warning(warningTemplate, "Retval"); } }
/*FIXME this constructor looks very broken in the position parameter*/ internal ParameterInfo (ParameterInfo pinfo, Type type, MemberInfo member, int position) { this.ClassImpl = type; this.MemberImpl = member; if (pinfo != null) { this.NameImpl = pinfo.Name; this.PositionImpl = pinfo.Position - 1; // ParameterInfo.Position is zero-based this.AttrsImpl = (ParameterAttributes) pinfo.Attributes; } else { this.NameImpl = null; this.PositionImpl = position - 1; this.AttrsImpl = ParameterAttributes.None; } }
// Constructor. internal ParameterBuilder(TypeBuilder type, MethodBase method, int position, ParameterAttributes attributes, String strParamName) { // Initialize the internal state. this.type = type; this.method = method; // Register this item to be detached later. type.module.assembly.AddDetach(this); // Create the parameter. lock(typeof(AssemblyBuilder)) { this.privateData = ClrParameterCreate (((IClrProgramItem)method).ClrHandle, position, attributes, strParamName); } }
public void TestDefineParameter() { string name = "Assembly1"; AssemblyName asmname = new AssemblyName(); asmname.Name = name; AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run); ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1"); TypeBuilder tpbuild = modbuild.DefineType("C1", TypeAttributes.Public); Type[] paramTypes = new Type[] { typeof(string), typeof(object) }; string[] paramNames = new string[] { "Param1", "Param2" }; ParameterAttributes[] paramAttrs = new ParameterAttributes[] { ParameterAttributes.In, ParameterAttributes.Out }; Type returnType = typeof(int); ParameterAttributes returnAttrs = ParameterAttributes.None; MethodBuilder methbuild = tpbuild.DefineMethod("meth1", MethodAttributes.Public | MethodAttributes.Static, returnType, paramTypes); methbuild.DefineParameter(0, returnAttrs, "returnName"); methbuild.DefineParameter(1, paramAttrs[0], paramNames[0]); methbuild.DefineParameter(2, paramAttrs[1], paramNames[1]); int expectedRet = 3; ILGenerator ilgen = methbuild.GetILGenerator(); ilgen.Emit(OpCodes.Ldc_I4, expectedRet); ilgen.Emit(OpCodes.Ret); Type tp = tpbuild.CreateTypeInfo().AsType(); ParameterInfo[] paramArray = methbuild.GetParameters(); Assert.Equal("System.String Param1", paramArray[0].ToString()); Assert.Equal("System.Object Param2", paramArray[1].ToString()); // invoke method to verify it still works correctly MethodInfo mi = tp.GetMethod("meth1"); int ret = (int)mi.Invoke(null, new object[] { "hello", new object() }); Assert.Equal(expectedRet, ret); }
public void TestThrowsExceptionForTypeCreated() { string name = "Assembly1"; AssemblyName asmname = new AssemblyName(); asmname.Name = name; AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run); ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1"); TypeBuilder tpbuild = modbuild.DefineType("C1", TypeAttributes.Public); Type[] paramTypes = new Type[] { typeof(string), typeof(object) }; string[] paramNames = new string[] { "Param1", "Param2" }; ParameterAttributes[] paramAttrs = new ParameterAttributes[] { ParameterAttributes.In, ParameterAttributes.Out }; Type returnType = typeof(int); MethodBuilder methbuild = tpbuild.DefineMethod("meth1", MethodAttributes.Public, returnType, paramTypes); ILGenerator ilgen = methbuild.GetILGenerator(); ilgen.Emit(OpCodes.Ret); Type tp = tpbuild.CreateTypeInfo().AsType(); Assert.Throws<InvalidOperationException>(() => { methbuild.DefineParameter(1, ParameterAttributes.Retval, "param1"); }); }
public void DefineParameter_AllAttributes() { ParameterAttributes[] attributes = new ParameterAttributes[] { ParameterAttributes.HasDefault, ParameterAttributes.HasFieldMarshal, ParameterAttributes.In, ParameterAttributes.None, ParameterAttributes.Optional, ParameterAttributes.Out, ParameterAttributes.Retval }; TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); Type[] paramTypes = Enumerable.Repeat(typeof(int), attributes.Length).ToArray(); MethodBuilder method = type.DefineMethod("TestMethod", TestMethodAttributes, typeof(void), paramTypes); for (int i = 1; i < attributes.Length; ++i) { ParameterBuilder parameter = method.DefineParameter(i, attributes[i], "TestParam"); VerifyParameterBuilder(parameter, "TestParam", attributes[i], i); } }
public void TestForEveryParameterAtributeFlag() { string strParamName = null; ParameterAttributes[] attributes = new ParameterAttributes[] { ParameterAttributes.HasDefault, ParameterAttributes.HasFieldMarshal, ParameterAttributes.In, ParameterAttributes.None, ParameterAttributes.Optional, ParameterAttributes.Out, ParameterAttributes.Retval }; Type[] paramTypes = new Type[attributes.Length]; for (int i = 0; i < paramTypes.Length; ++i) { paramTypes[i] = typeof(int); } TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod( PosTestDynamicMethodName, TestMethodAttributes, typeof(void), paramTypes); for (int i = 1; i < attributes.Length; ++i) { strParamName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); ParameterBuilder paramBuilder = builder.DefineParameter(i, attributes[i], strParamName); Assert.NotNull(paramBuilder); VerifyParameterBuilder(paramBuilder, strParamName, attributes[i], i); } }
public override JniValueMarshalerState CreateArgumentState(object value, ParameterAttributes synchronize) { throw new NotSupportedException(); }
public void GetParamDefProps(int parameterToken, out int sequence, out ParameterAttributes attributes) { _GetParamDefProps(m_metadataImport2, parameterToken, out sequence, out int _attributes); attributes = (ParameterAttributes)_attributes; }
public ParameterDefinition(string name, ParameterAttributes attributes, TypeReference parameterType) : base(name, parameterType) { this.attributes = (ushort)attributes; this.token = new MetadataToken(TokenType.Param); }
private PEParameterSymbol( PEModuleSymbol moduleSymbol, Symbol containingSymbol, int ordinal, bool isByRef, TypeWithAnnotations typeWithAnnotations, ParameterHandle handle, Symbol nullableContext, int countOfCustomModifiers, out bool isBad) { Debug.Assert((object)moduleSymbol != null); Debug.Assert((object)containingSymbol != null); Debug.Assert(ordinal >= 0); Debug.Assert(typeWithAnnotations.HasType); isBad = false; _moduleSymbol = moduleSymbol; _containingSymbol = containingSymbol; _ordinal = (ushort)ordinal; _handle = handle; RefKind refKind = RefKind.None; DeclarationScope scope = DeclarationScope.Unscoped; if (handle.IsNil) { refKind = isByRef ? RefKind.Ref : RefKind.None; byte?value = nullableContext.GetNullableContextValue(); if (value.HasValue) { typeWithAnnotations = NullableTypeDecoder.TransformType(typeWithAnnotations, value.GetValueOrDefault(), default); } _lazyCustomAttributes = ImmutableArray <CSharpAttributeData> .Empty; _lazyHiddenAttributes = ImmutableArray <CSharpAttributeData> .Empty; _lazyDefaultValue = ConstantValue.NotAvailable; _lazyIsParams = ThreeState.False; } else { try { moduleSymbol.Module.GetParamPropsOrThrow(handle, out _name, out _flags); } catch (BadImageFormatException) { isBad = true; } if (isByRef) { ParameterAttributes inOutFlags = _flags & (ParameterAttributes.Out | ParameterAttributes.In); if (inOutFlags == ParameterAttributes.Out) { refKind = RefKind.Out; scope = DeclarationScope.RefScoped; } else if (moduleSymbol.Module.HasIsReadOnlyAttribute(handle)) { refKind = RefKind.In; } else { refKind = RefKind.Ref; } } var typeSymbol = DynamicTypeDecoder.TransformType(typeWithAnnotations.Type, countOfCustomModifiers, handle, moduleSymbol, refKind); typeSymbol = NativeIntegerTypeDecoder.TransformType(typeSymbol, handle, moduleSymbol, containingSymbol.ContainingType); typeWithAnnotations = typeWithAnnotations.WithTypeAndModifiers(typeSymbol, typeWithAnnotations.CustomModifiers); // Decode nullable before tuple types to avoid converting between // NamedTypeSymbol and TupleTypeSymbol unnecessarily. // The containing type is passed to NullableTypeDecoder.TransformType to determine access // for property parameters because the property does not have explicit accessibility in metadata. var accessSymbol = containingSymbol.Kind == SymbolKind.Property ? containingSymbol.ContainingSymbol : containingSymbol; typeWithAnnotations = NullableTypeDecoder.TransformType(typeWithAnnotations, handle, moduleSymbol, accessSymbol: accessSymbol, nullableContext: nullableContext); typeWithAnnotations = TupleTypeDecoder.DecodeTupleTypesIfApplicable(typeWithAnnotations, handle, moduleSymbol); if (_moduleSymbol.Module.HasLifetimeAnnotationAttribute(_handle, out var pair)) { var scopeOpt = GetScope(refKind, typeWithAnnotations.Type, pair.IsRefScoped, pair.IsValueScoped); if (scopeOpt is null) { isBad = true; } else { scope = scopeOpt.GetValueOrDefault(); } } } _typeWithAnnotations = typeWithAnnotations; bool hasNameInMetadata = !string.IsNullOrEmpty(_name); if (!hasNameInMetadata) { // As was done historically, if the parameter doesn't have a name, we give it the name "value". _name = "value"; } _packedFlags = new PackedFlags(refKind, attributesAreComplete: handle.IsNil, hasNameInMetadata: hasNameInMetadata, scope); Debug.Assert(refKind == this.RefKind); Debug.Assert(hasNameInMetadata == this.HasNameInMetadata); Debug.Assert(_name is not null); }
public virtual void SetMarshal(UnmanagedMarshal unmanagedMarshal) { marshal_info = unmanagedMarshal; attrs |= ParameterAttributes.HasFieldMarshal; }
/// <summary> /// takes a mbuilder for output, the input assembly, the name of the type, /// and a flag indicating whether it's an instance type or not (i.e. whether /// the members should be static or not. /// /// It then munges mercilessly. /// </summary> /// <param name="mbuilder"></param> /// <param name="inputAssembly"></param> /// <param name="typeName"></param> /// <param name="isInstanceClass"></param> public static void ProcessType(ModuleBuilder mbuilder, Assembly inputAssembly, string typeName, bool isInstanceClass) { TypeBuilder glbuilder = mbuilder.DefineType(typeName, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed); glbuilder.SetCustomAttribute(GetCLSCompliantCAB(true)); Type gltype = inputAssembly.GetType(typeName); MemberInfo [] glMembers = gltype.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); // just something to help us print some status.. int methodCount = 0; Console.Write("Processing {0}...", typeName); foreach (MemberInfo qi in glMembers) { // Fields FieldInfo fi = qi as FieldInfo; if (fi != null) { // Console.WriteLine ("FIELD: " + fi.Name); FieldBuilder fb = glbuilder.DefineField(fi.Name, fi.FieldType, fi.Attributes); // only set constants in the non-instance class if (fi.FieldType != typeof(System.IntPtr) && !isInstanceClass) { fb.SetConstant(fi.GetValue(gltype)); } else { object [] extattrs = fi.GetCustomAttributes(typeof(OpenGl.OpenGLExtensionImport), false); if (extattrs.Length > 0) { OpenGl.OpenGLExtensionImport ogl = extattrs[0] as OpenGl.OpenGLExtensionImport; if (ogl == null) { throw new InvalidProgramException("Thought we had an attr, guess we were wrong!"); } fb.SetCustomAttribute(CreateGLExtCAB(ogl.ExtensionName, ogl.EntryPoint)); } // this is a slot to hold an extension addr, // so we save it. We have to do this because on // windows we can't call GetField on a dynamic type. // This is probably faster anyway. field_hash[fi.Name] = fb; } continue; } // Methods MethodInfo mi = qi as MethodInfo; if (mi != null) { bool is_ext; bool is_dll; bool is_cls_compliant; object [] extattrs = mi.GetCustomAttributes(typeof(OpenGl.OpenGLExtensionImport), false); object [] clsattrs = mi.GetCustomAttributes(typeof(CLSCompliantAttribute), false); is_ext = (extattrs.Length > 0); is_dll = (mi.Attributes & MethodAttributes.PinvokeImpl) != 0; if (clsattrs.Length > 0) { is_cls_compliant = (clsattrs[0] as CLSCompliantAttribute).IsCompliant; } else { is_cls_compliant = true; } ParameterInfo [] parms = mi.GetParameters(); Type [] methodSig = new Type [parms.Length]; ParameterAttributes [] methodParams = new ParameterAttributes [parms.Length]; for (int i = 0; i < parms.Length; i++) { methodSig[i] = parms[i].ParameterType; methodParams[i] = parms[i].Attributes; } // Console.WriteLine ("Method: {0} is_dll: {1}", mi.Name, is_dll); if (is_dll) { // this is a normal DLL import'd method // Console.WriteLine ("DLL import method: " + mi.Name); MethodBuilder mb = glbuilder.DefinePInvokeMethod(mi.Name, GL_NATIVE_LIBRARY, mi.Name, mi.Attributes, CallingConventions.Standard, mi.ReturnType, methodSig, CallingConvention.Winapi, CharSet.Ansi); mb.SetImplementationFlags(mb.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig); // Set In/Out/etc. back for (int i = 0; i < parms.Length; i++) { mb.DefineParameter(i + 1, methodParams[i], null); } mb.SetCustomAttribute(GetSuppressUnmanagedCSCAB()); if (is_cls_compliant) { mb.SetCustomAttribute(GetCLSCompliantCAB(true)); } else { mb.SetCustomAttribute(GetCLSCompliantCAB(false)); } } else if (is_ext) { // this is an OpenGLExtensionImport method OpenGl.OpenGLExtensionImport ogl = extattrs[0] as OpenGl.OpenGLExtensionImport; if (ogl == null) { throw new InvalidProgramException("Thought we had an OpenGLExtensionImport, guess not?"); } // Console.WriteLine ("OpenGL Extension method: " + mi.Name); MethodBuilder mb = glbuilder.DefineMethod(mi.Name, mi.Attributes, mi.ReturnType, methodSig); // Set In/Out/etc. back for (int i = 0; i < parms.Length; i++) { mb.DefineParameter(i + 1, methodParams[i], null); } // put attributes mb.SetCustomAttribute(GetSuppressUnmanagedCSCAB()); if (is_cls_compliant) { mb.SetCustomAttribute(GetCLSCompliantCAB(true)); } else { mb.SetCustomAttribute(GetCLSCompliantCAB(false)); } // now build the IL string fieldname = "ext__" + ogl.ExtensionName + "__" + ogl.EntryPoint; FieldInfo addrfield = field_hash[fieldname] as FieldInfo; // no workie on win32; the field_hash is probably faster anyway // FieldInfo addrfield = glbuilder.GetField(fieldname, // BindingFlags.Instance | // BindingFlags.Static | // BindingFlags.Public | // BindingFlags.NonPublic | // BindingFlags.DeclaredOnly); ILGenerator ilg = mb.GetILGenerator(); ArrayList locals = new ArrayList(); Type [] methodCalliSig = new Type[methodSig.Length]; int thislocal; int numargs = methodSig.Length; int argoffset = 0; if (isInstanceClass) { argoffset = 1; } for (int arg = argoffset; arg < numargs; arg++) { EmitLdarg(ilg, arg); // we need to convert strings and string arrays to C // null-terminated strings. Use StringToHGlobalAnsi // from Marshal. We don't handle byref string arrays; // there are so few (any?) of them that we can just // return an IntPtr. if (methodSig[arg].IsArray && methodSig[arg].GetElementType() == typeof(string)) { //Console.WriteLine ("String[] param: Method: {0} Param: {1} Type: {2}", mi.Name, arg - argoffset, methodSig[arg]); if (locals.Count == 0) { locals.Add(ilg.DeclareLocal(typeof(int))); } thislocal = locals.Count; locals.Add(ilg.DeclareLocal(typeof(IntPtr[]))); // we have the source array on the stack; get its length, // and allocate a new IntPtr array ilg.Emit(OpCodes.Ldlen); ilg.Emit(OpCodes.Conv_I4); ilg.Emit(OpCodes.Newarr, typeof(IntPtr)); EmitStloc(ilg, thislocal); // set our loop counter to 0; ilg.Emit(OpCodes.Ldc_I4_0); EmitStloc(ilg, 0); // declare our loop label; we'll branch // back to here after each conversion Label loop = ilg.DefineLabel(); ilg.MarkLabel(loop); // put the address of the destination element onto the stack EmitLdloc(ilg, thislocal); EmitLdloc(ilg, 0); ilg.Emit(OpCodes.Ldelema, typeof(IntPtr)); // put the source string on the stack EmitLdarg(ilg, arg); EmitLdloc(ilg, 0); ilg.Emit(OpCodes.Ldelem_Ref); // convert ilg.EmitCall(OpCodes.Call, GetStringMarshalMI(), null); // store the result into the address we put up above ilg.Emit(OpCodes.Stobj, typeof(IntPtr)); // add 1 to loop counter EmitLdloc(ilg, 0); ilg.Emit(OpCodes.Ldc_I4_1); ilg.Emit(OpCodes.Add); ilg.Emit(OpCodes.Dup); EmitStloc(ilg, 0); // test if loop counter < array length, and branch back // to start of loop EmitLdarg(ilg, arg); ilg.Emit(OpCodes.Ldlen); ilg.Emit(OpCodes.Conv_I4); ilg.Emit(OpCodes.Blt, loop); // finally emit the location of the first element of the array EmitLdloc(ilg, thislocal); ilg.Emit(OpCodes.Ldc_I4_0); ilg.Emit(OpCodes.Ldelema, typeof(IntPtr)); methodCalliSig[arg] = typeof(IntPtr); } else if (methodSig[arg].IsByRef && methodSig[arg].GetElementType() == typeof(string)) { //Console.WriteLine ("String& param: Method: {0} Param: {1} Type: {2}", mi.Name, arg - argoffset, methodSig[arg]); //if (locals.Count == 0) locals.Add(ilg.DeclareLocal(typeof(int))); //thislocal = locals.Count; //locals.Add(ilg.DeclareLocal(typeof(IntPtr))); //methodCalliSig[arg] = typeof(IntPtr); } else if (methodSig[arg] == typeof(string)) { //Console.WriteLine ("String param: Method: {0} Param: {1} Type: {2}", mi.Name, arg - argoffset, methodSig[arg]); if (locals.Count == 0) { locals.Add(ilg.DeclareLocal(typeof(int))); } thislocal = locals.Count; locals.Add(ilg.DeclareLocal(typeof(IntPtr))); ilg.EmitCall(OpCodes.Call, GetStringMarshalMI(), null); ilg.Emit(OpCodes.Dup); EmitStloc(ilg, thislocal); methodCalliSig[arg] = typeof(IntPtr); } else { methodCalliSig[arg] = methodSig[arg]; } } if (isInstanceClass) { // load the instance field ilg.Emit(OpCodes.Ldarg_0); ilg.Emit(OpCodes.Ldfld, addrfield); } else { // just load the static field ilg.Emit(OpCodes.Ldsfld, addrfield); } // emit Tailcall; have the return take place directly to our // caller, but only if we have no marshal'd things to clean up if (locals.Count == 0) { ilg.Emit(OpCodes.Tailcall); methodCalliSig = methodSig; } // The .NET 1.1 runtime doesn't let us emit // CallingConvention.Winapi here, or anything else that // might mean "Use whatever the default platform calling // convention is", like p/invoke can have. // // However, Mono 1.1 /does/ let us emit Winapi/Default, // and both .NET 1.1 and Mono handle this as intended // (stdcall on .NET, cdecl on Mono/Linux). By my reading // of ECMA-335 (CLI), 22.2.2, this should be allowed, and // I'm not sure why MS's impl doesn't allow it. However, // the .NET System.Reflection.Emit leaves a lot to be // desired anyway. // // So, the issue is how to emit this. On WIN32, we simply // create our own SignatureHelper, and munge the internal // signature byte. Fun, eh? // // ... Except that it doesn't quite work that way. The runtime // gets confused by the calling convention. // #if !WIN32 // Mono? Just emit normally. ilg.EmitCalli(OpCodes.Calli, CallingConvention.Winapi, mi.ReturnType, methodCalliSig); #else // We're too smart for our own good. We don't tell win32 how to do stack // cleanup, so it leaves things littering the stack. So, we can't do this. // GRRRrrr. #if true ilg.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, mi.ReturnType, methodCalliSig); #else // Win32? Let the fun begin. if (win32SigField == null) { win32SigField = typeof(SignatureHelper).GetField("m_signature", BindingFlags.Instance | BindingFlags.NonPublic); } SignatureHelper sh = SignatureHelper.GetMethodSigHelper(mbuilder, CallingConvention.StdCall, // lie mi.ReturnType); // munge calling convention; the value in the first byte will be 0x2 for StdCall (1 minus // the CallingConvention enum value). We set to 0. Array sigArr = win32SigField.GetValue(sh) as Array; sigArr.SetValue((byte)0, 0); // then add the rest of the args. foreach (Type t in methodCalliSig) { sh.AddArgument(t); } ilg.Emit(OpCodes.Calli, sh); #endif #endif // clean up our string allocations, if any if (locals.Count > 0) { for (int i = 1; i < locals.Count; i++) { Type ltype = (locals[i] as LocalBuilder).LocalType; if (ltype.IsArray) { Label looptest = ilg.DefineLabel(); Label loop = ilg.DefineLabel(); // counter = array.Length EmitLdloc(ilg, i); ilg.Emit(OpCodes.Ldlen); ilg.Emit(OpCodes.Conv_I4); EmitStloc(ilg, 0); // goto looptest ilg.Emit(OpCodes.Br, looptest); ilg.MarkLabel(loop); // free(array[counter]) EmitLdloc(ilg, i); EmitLdloc(ilg, 0); ilg.Emit(OpCodes.Ldelem_I4); ilg.EmitCall(OpCodes.Call, GetFreeGlobalMI(), null); ilg.MarkLabel(looptest); // p = counter; counter -= 1; EmitLdloc(ilg, 0); ilg.Emit(OpCodes.Dup); ilg.Emit(OpCodes.Ldc_I4_1); ilg.Emit(OpCodes.Sub); EmitStloc(ilg, 0); // if (p > 0) goto loop ilg.Emit(OpCodes.Ldc_I4_0); ilg.Emit(OpCodes.Bgt, loop); } else { // just a simple free, thankfully EmitLdloc(ilg, i); ilg.EmitCall(OpCodes.Call, GetFreeGlobalMI(), null); } } } ilg.Emit(OpCodes.Ret); } else { // this is a normal method // this shouldn't happen Console.WriteLine(); Console.WriteLine("WARNING: Skipping non-DLL and non-Extension method " + mi.Name); } methodCount++; if (methodCount % 50 == 0) { Console.Write("."); } if (methodCount % 1000 == 0) { Console.Write("[{0}]", methodCount); } } } Console.WriteLine(); glbuilder.CreateType(); Console.WriteLine("Type created."); }
public override Expression CreateParameterFromManagedExpression(JniValueMarshalerContext context, ParameterExpression sourceValue, ParameterAttributes synchronize) { return(sourceValue); }
internal void SetAttributes(ParameterAttributes attributes) { AttrsImpl = attributes; }
public virtual void SetConstant (object defaultValue) { if (position > 0) { Type t = methodb.GetParameterType (position - 1); if (defaultValue != null && t != defaultValue.GetType ()) throw new ArgumentException ("Constant does not match the defined type."); if (t.IsValueType && !t.IsPrimitive && !t.IsEnum && t != typeof (DateTime)) throw new ArgumentException ("" + t + " is not a supported constant type."); } def_value = defaultValue; attrs |= ParameterAttributes.HasDefault; }
public override JniValueMarshalerState CreateGenericObjectReferenceArgumentState(SByte value, ParameterAttributes synchronize) { var r = JniByte.CreateLocalRef(value); return(new JniValueMarshalerState(r)); }
public void DefineParameter(string name, ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3) { writer.DefineParameter(name, (uint)attributes, (uint)sequence, (uint)addrKind, (uint)addr1, (uint)addr2, (uint)addr3); }
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string strParamName) { return(methodBuilder.DefineParameter(position, attributes, strParamName)); }
public override Expression CreateParameterToManagedExpression(Java.Interop.Expressions.JniValueMarshalerContext context, ParameterExpression sourceValue, ParameterAttributes synchronize, Type targetType) { return(sourceValue); }
public ParamRow(ParameterAttributes attributes, ushort sequence, uint name) : this() { Attributes = attributes; Sequence = sequence; Name = name; }
protected override ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string parameterName) { return(mb.DefineParameter(position, attributes, parameterName)); }
private PEParameterSymbol( PEModuleSymbol moduleSymbol, Symbol containingSymbol, int ordinal, bool isByRef, TypeSymbolWithAnnotations type, ImmutableArray <byte> extraAnnotations, ParameterHandle handle, int countOfCustomModifiers, out bool isBad) { Debug.Assert((object)moduleSymbol != null); Debug.Assert((object)containingSymbol != null); Debug.Assert(ordinal >= 0); Debug.Assert(!type.IsNull); isBad = false; _moduleSymbol = moduleSymbol; _containingSymbol = containingSymbol; _ordinal = (ushort)ordinal; _handle = handle; RefKind refKind = RefKind.None; if (handle.IsNil) { refKind = isByRef ? RefKind.Ref : RefKind.None; type = TupleTypeSymbol.TryTransformToTuple(type.TypeSymbol, out TupleTypeSymbol tuple) ? TypeSymbolWithAnnotations.Create(tuple) : type; if (!extraAnnotations.IsDefault) { type = NullableTypeDecoder.TransformType(type, defaultTransformFlag: 0, extraAnnotations); } _lazyCustomAttributes = ImmutableArray <CSharpAttributeData> .Empty; _lazyHiddenAttributes = ImmutableArray <CSharpAttributeData> .Empty; _lazyDefaultValue = ConstantValue.NotAvailable; _lazyIsParams = ThreeState.False; } else { try { moduleSymbol.Module.GetParamPropsOrThrow(handle, out _name, out _flags); } catch (BadImageFormatException) { isBad = true; } if (isByRef) { ParameterAttributes inOutFlags = _flags & (ParameterAttributes.Out | ParameterAttributes.In); if (inOutFlags == ParameterAttributes.Out) { refKind = RefKind.Out; } else if (moduleSymbol.Module.HasIsReadOnlyAttribute(handle)) { refKind = RefKind.In; } else { refKind = RefKind.Ref; } } // CONSIDER: Can we make parameter type computation lazy? var typeSymbol = DynamicTypeDecoder.TransformType(type.TypeSymbol, countOfCustomModifiers, handle, moduleSymbol, refKind); type = type.WithTypeAndModifiers(typeSymbol, type.CustomModifiers); // Decode nullable before tuple types to avoid converting between // NamedTypeSymbol and TupleTypeSymbol unnecessarily. type = NullableTypeDecoder.TransformType(type, handle, moduleSymbol, extraAnnotations); type = TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, handle, moduleSymbol); } _type = type; bool hasNameInMetadata = !string.IsNullOrEmpty(_name); if (!hasNameInMetadata) { // As was done historically, if the parameter doesn't have a name, we give it the name "value". _name = "value"; } _packedFlags = new PackedFlags(refKind, attributesAreComplete: handle.IsNil, hasNameInMetadata: hasNameInMetadata); Debug.Assert(refKind == this.RefKind); Debug.Assert(hasNameInMetadata == this.HasNameInMetadata); }
/// <summary> /// Initializes a new instance of the <see cref="ParamRow" /> struct. /// </summary> /// <param name="flags">The flags.</param> /// <param name="sequence">The sequence.</param> /// <param name="name">The name.</param> public ParamRow(ParameterAttributes flags, short sequence, HeapIndexToken name) { Name = name; Sequence = sequence; Flags = flags; }
/// <summary> /// Generates a method on our <see cref="TypeBuilder"/> for the specified <see cref="MethodInfo"/> /// </summary> /// <param name="tb">The <see cref="TypeBuilder"/> we're generating our type with.</param> /// <param name="mi">The <see cref="MethodInfo"/> which represents the "template" method.</param> /// <param name="dllName">The path to the DLL that we'll put in the <see cref="DllImportAttribute"/>.</param> private static void GenerateMethod(TypeBuilder tb, MethodInfo mi, string dllName) { // These are all the parameters in our method var pis = new List <ParameterInfo>(mi.GetParameters()); // We need to keep the parameter types and attributes in a separate array. var ptypes = new Type[pis.Count]; var attrs = new ParameterAttributes[pis.Count]; for (var i = 0; i < pis.Count; i++) { ptypes[i] = pis[i].ParameterType; attrs[i] = pis[i].Attributes; } // We actually need to create TWO methods - one for the interface implementation, and one for the // P/Invoke declaration. We'll create the P/Invoke definition first. var smb = tb.DefineMethod( mi.Name, // The name is the same as the interface name // P/Invoke methods need special attributes... MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig, mi.ReturnType, ptypes); // Get the type of the DllImportAttribute, which we'll attach to this method var diaType = typeof(DllImportAttribute); // Create a CustomAttributeBuilder for the DLLImportAttribute, specifying the constructor that takes a string argument. var ctor = diaType.GetConstructor(new Type[] { typeof(string) }); var cab = new CustomAttributeBuilder(ctor, new object[] { dllName }); // Assign the DllImport attribute to the smb smb.SetCustomAttribute(cab); // Also, any attributes on the actual parameters need to be copied to the P/Invoke declaration as well. for (var i = 0; i < attrs.Length; i++) { smb.DefineParameter(i + 1, attrs[i], pis[i].Name); } // Now create the interface implementation method var mb = tb.DefineMethod( "IFbClient." + mi.Name, // We use the standard "Interface.Method" to do an explicit interface implementation MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, mi.ReturnType, ptypes); // Also, any attributes on the actual parameters need to be copied to the P/Invoke declaration as well. for (var i = 0; i < attrs.Length; i++) { mb.DefineParameter(i + 1, attrs[i], pis[i].Name); } // We need to generate a little IL here to actually call the P/Invoke declaration. Luckily for us, since we're just // going to pass our parameters to the P/Invoke method as-is, we don't need to muck with the eval stack ;-) var il = mb.GetILGenerator(); for (var i = 1; i <= pis.Count; i++) { EmitLdarg(il, i); } il.EmitCall(OpCodes.Call, smb, null); EmitClientInjectionToFirebirdHandleOjects(mi.ReturnType, pis, il); il.Emit(OpCodes.Ret); // Define the fact that our IFbClient.Method is the explicit interface implementation of that method tb.DefineMethodOverride(mb, mi); }
private static void VerifyParameterBuilder(ParameterBuilder parameter, string expectedName, ParameterAttributes expectedAttributes, int expectedPosition) { // This constant maps to ParameterAttributes.ReservedMask that is not available in the contract. const int ReservedMaskParameterAttribute = 0xF000; Assert.Equal(expectedName, parameter.Name); int removedReservedAttributes = (int)expectedAttributes & ~ReservedMaskParameterAttribute; Assert.Equal(removedReservedAttributes, (parameter.Attributes & removedReservedAttributes)); Assert.Equal(expectedPosition, parameter.Position); }
public virtual void SetMarshal( UnmanagedMarshal unmanagedMarshal) { marshal_info = unmanagedMarshal; attrs |= ParameterAttributes.HasFieldMarshal; }
public void SetAttrsImpl(ParameterAttributes a) { AttrsImpl = a; }
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string name) => _base.DefineParameter(position, attributes, name);
public void DefineParameter_NoParameters_NonZeroPosition_ThrowsArgumentOutOfRangeException(TypeAttributes typeAttributes, MethodAttributes methodAttributes, ParameterAttributes parameterAttributes) { TypeBuilder type = Helpers.DynamicType(typeAttributes); MethodBuilder method = type.DefineMethod("TestMethod", methodAttributes); Assert.Throws <ArgumentOutOfRangeException>(() => method.DefineParameter(1, parameterAttributes, "Param1")); Assert.Throws <ArgumentOutOfRangeException>(() => method.DefineParameter(-1, parameterAttributes, "Param1")); }
public override JniValueMarshalerState CreateGenericObjectReferenceArgumentState(IntPtr value, ParameterAttributes synchronize) { throw new NotSupportedException(); }
public ParameterDescriptor(Type type, ParameterAttributes attributes) : this(type, attributes, null) { }
public override JniValueMarshalerState CreateGenericObjectReferenceArgumentState(Char?value, ParameterAttributes synchronize) { if (!value.HasValue) { return(new JniValueMarshalerState()); } var r = JniCharacter.CreateLocalRef(value.Value); return(new JniValueMarshalerState(r)); }
public override void DestroyGenericArgumentState(IntPtr value, ref JniValueMarshalerState state, ParameterAttributes synchronize) { throw new NotSupportedException(); }
public void SetCustomAttribute( CustomAttributeBuilder customBuilder) { string attrname = customBuilder.Ctor.ReflectedType.FullName; if (attrname == "System.Runtime.InteropServices.InAttribute") { attrs |= ParameterAttributes.In; return; } else if (attrname == "System.Runtime.InteropServices.OutAttribute") { attrs |= ParameterAttributes.Out; return; } else if (attrname == "System.Runtime.InteropServices.OptionalAttribute") { attrs |= ParameterAttributes.Optional; return; } else if (attrname == "System.Runtime.InteropServices.MarshalAsAttribute") { attrs |= ParameterAttributes.HasFieldMarshal; marshal_info = CustomAttributeBuilder.get_umarshal (customBuilder, false); /* FIXME: check for errors */ return; } else if (attrname == "System.Runtime.InteropServices.DefaultParameterValueAttribute") { /* MS.NET doesn't handle this attribute but we handle it for consistency */ CustomAttributeBuilder.CustomAttributeInfo cinfo = CustomAttributeBuilder.decode_cattr (customBuilder); /* FIXME: check for type compatibility */ SetConstant (cinfo.ctorArgs [0]); return; } if (cattrs != null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; cattrs.CopyTo (new_array, 0); new_array [cattrs.Length] = customBuilder; cattrs = new_array; } else { cattrs = new CustomAttributeBuilder [1]; cattrs [0] = customBuilder; } }
public void DefineParameter(string name, ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3) { throw new Exception("The method or operation is not implemented."); }
public override JniValueMarshalerState CreateGenericArgumentState([MaybeNull] IntPtr value, ParameterAttributes synchronize) { throw new NotSupportedException(); }
public void DefineParameter_InvalidPosition_ThrowsArgumentOutOfRangeException(TypeAttributes typeAttributes, MethodAttributes methodAttributes, ParameterAttributes parameterAttributes, Type[] paramTypes, Type returnType) { TypeBuilder type = Helpers.DynamicType(typeAttributes); MethodBuilder method = type.DefineMethod("TestMethod", methodAttributes, returnType, paramTypes); Assert.Throws <ArgumentOutOfRangeException>(() => method.DefineParameter(-1, parameterAttributes, "Param1")); Assert.Throws <ArgumentOutOfRangeException>(() => method.DefineParameter(paramTypes.Length + 1, parameterAttributes, "Param1")); }
public override JniValueMarshalerState CreateGenericArgumentState(Char value, ParameterAttributes synchronize = ParameterAttributes.In) { return(new JniValueMarshalerState(new JniArgumentValue(value))); }
public override void DestroyGenericArgumentState(Char value, ref JniValueMarshalerState state, ParameterAttributes synchronize) { var r = state.ReferenceValue; JniObjectReference.Dispose(ref r); state = new JniValueMarshalerState(); }