Esempio n. 1
1
        internal static MethodInvoker Create(MethodInfo method, object target)
        {

            var args = new List<Type>(method.GetParameters().Select(p => p.ParameterType));
            Type delegateType;

            var returnMethodInvoker = new MethodInvoker
            {
                ParameterTypeList = args.ToList(),
                ParameterCount = args.Count,
                ReturnType = method.ReturnType,
                MethodName = method.Name
            };


            if (method.ReturnType == typeof(void))
            {
                delegateType = Expression.GetActionType(args.ToArray());
            }
            else
            {
                args.Add(method.ReturnType);
                delegateType = Expression.GetFuncType(args.ToArray());
            }

            returnMethodInvoker.MethodDelegate = method.CreateDelegate(delegateType, target);

            return returnMethodInvoker;

        }
        static StackObject *CreateDelegate_13(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Object @target = (System.Object) typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Type @delegateType = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Reflection.MethodInfo instance_of_this_method = (System.Reflection.MethodInfo) typeof(System.Reflection.MethodInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.CreateDelegate(@delegateType, @target);

            object obj_result_of_this_method = result_of_this_method;

            if (obj_result_of_this_method is CrossBindingAdaptorType)
            {
                return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Esempio n. 3
0
            private static Expression CreateDelegateExpr(System.Reflection.MethodInfo target)
            {
                var types = new List <Type>();

                types.Add(target.DeclaringType);
                types.AddRange(target.GetParameters().Select(x => x.ParameterType));
                Type delegateType;

                if (target.ReturnType == typeof(void))
                {
                    delegateType = Expression.GetActionType(types.ToArray());
                }
                else
                {
                    types.Add(target.ReturnType);
                    delegateType = Expression.GetFuncType(types.ToArray());
                }

                var deleg = target.CreateDelegate(delegateType);

                var delegateExpr = Expression.Constant(deleg);
                var conversion   = Expression.Convert(delegateExpr, delegateType);

                var delegateCreator = Expression.Lambda(conversion).Compile();
                var methodClojure   = Expression.Constant(delegateCreator.DynamicInvoke());

                return(methodClojure);
            }
 public InvokableCall(object target, MethodInfo theFunction)
   : base(target, theFunction)
 {
   InvokableCall invokableCall = this;
   UnityAction unityAction = (UnityAction) System.Delegate.Combine((System.Delegate) invokableCall.Delegate, theFunction.CreateDelegate(typeof (UnityAction), target));
   invokableCall.Delegate = unityAction;
 }
Esempio n. 5
0
        internal static Delegate CreateDelegate(object firstArgument, MethodInfo mi)
        {
            if ((mi.CallingConvention & CallingConventions.VarArgs) != 0)
                throw new ArgumentException("Call of VarArgs not implemented.");

            return mi.CreateDelegate(GetDelegateType(mi), firstArgument);
        }
Esempio n. 6
0
        internal static Delegate CreateDelegate(Type delegateType, System.Reflection.MethodInfo method)
        {
#if COREFX
            return(method.CreateDelegate(delegateType));
#else
            return(Delegate.CreateDelegate(delegateType, method));
#endif
        }
Esempio n. 7
0
        public static Delegate CreateDelegate(Type type, object target, MethodInfo method)
        {
#if NET4
            return Delegate.CreateDelegate(type, target, method);
#else
            return method.CreateDelegate(type, target);
#endif
        }
Esempio n. 8
0
        /// <summary>
        /// Hack for compatibility RabbitMQ.Client library between 3.4.x and 3.5.x versions
        /// ConnectionShutdownEventHandler replaced by Eventhandler<ShutdownEventArgs> - https://github.com/rabbitmq/rabbitmq-dotnet-client/commit/84ca5552a338a86c9af124331adca230accf3be3
        /// using reflection for understand, what type of delegate we must use for IConnection.ConnectionShutdown:
        /// - EventHandler<ShutdownEventArgs> for 3.5.x version
        /// - ConnectionShutdownEventHandler for 3.4.x and early version
        /// </summary>
        private void PrepareConnectionShutdownEventHandler()
        {
            System.Reflection.EventInfo connectionShutdownEventInfo = typeof(IConnection).GetEvent("ConnectionShutdown");
            _connectionShutdownEventAddMethod = connectionShutdownEventInfo.GetAddMethod();

            Type delegateType = connectionShutdownEventInfo.EventHandlerType;

            System.Reflection.MethodInfo shutdownAmqpMethodInfo = null;

            if (delegateType.IsConstructedGenericType && delegateType.GetGenericTypeDefinition() == typeof(EventHandler <>))
            {
                shutdownAmqpMethodInfo = typeof(RabbitMQ).GetMethod("ShutdownAmqp35", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            }
            else
            {
                shutdownAmqpMethodInfo = typeof(RabbitMQ).GetMethod("ShutdownAmqp", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            }

            _connectionShutdownEventHandler = shutdownAmqpMethodInfo.CreateDelegate(delegateType, this);
        }
Esempio n. 9
0
 public static Delegate CreateDelegate(Type type, MethodInfo method)
 {
     return method.CreateDelegate(type);
 }
Esempio n. 10
0
	/// <summary>
	/// Cache the callback and create the list of the necessary parameters.
	/// </summary>

	void Cache ()
	{
		mCached = true;
		if (mRawDelegate) return;

#if REFLECTION_SUPPORT
		if (mCachedCallback == null || (mCachedCallback.Target as MonoBehaviour) != mTarget || GetMethodName(mCachedCallback) != mMethodName)
		{
			if (mTarget != null && !string.IsNullOrEmpty(mMethodName))
			{
				System.Type type = mTarget.GetType();
 #if NETFX_CORE
				try
				{
					IEnumerable<MethodInfo> methods = type.GetRuntimeMethods();

					foreach (MethodInfo mi in methods)
					{
						if (mi.Name == mMethodName)
						{
							mMethod = mi;
							break;
						}
					}
				}
				catch (System.Exception ex)
				{
					Debug.LogError("Failed to bind " + type + "." + mMethodName + "\n" +  ex.Message);
					return;
				}
 #else // NETFX_CORE
				for (mMethod = null; type != null; )
				{
					try
					{
						mMethod = type.GetMethod(mMethodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
						if (mMethod != null) break;
					}
					catch (System.Exception) { }
  #if UNITY_WP8 || UNITY_WP_8_1
					// For some odd reason Type.GetMethod(name, bindingFlags) doesn't seem to work on WP8...
					try
					{
						mMethod = type.GetMethod(mMethodName);
						if (mMethod != null) break;
					}
					catch (System.Exception) { }
  #endif
					type = type.BaseType;
				}
 #endif // NETFX_CORE

				if (mMethod == null)
				{
					Debug.LogError("Could not find method '" + mMethodName + "' on " + mTarget.GetType(), mTarget);
					return;
				}
				
				if (mMethod.ReturnType != typeof(void))
				{
					Debug.LogError(mTarget.GetType() + "." + mMethodName + " must have a 'void' return type.", mTarget);
					return;
				}

				// Get the list of expected parameters
				mParameterInfos = mMethod.GetParameters();

				if (mParameterInfos.Length == 0)
				{
					// No parameters means we can create a simple delegate for it, optimizing the call
 #if NETFX_CORE
					mCachedCallback = (Callback)mMethod.CreateDelegate(typeof(Callback), mTarget);
 #else
					mCachedCallback = (Callback)System.Delegate.CreateDelegate(typeof(Callback), mTarget, mMethodName);
 #endif

					mArgs = null;
					mParameters = null;
					return;
				}
				else mCachedCallback = null;

				// Allocate the initial list of parameters
				if (mParameters == null || mParameters.Length != mParameterInfos.Length)
				{
					mParameters = new Parameter[mParameterInfos.Length];
					for (int i = 0, imax = mParameters.Length; i < imax; ++i)
						mParameters[i] = new Parameter();
				}

				// Save the parameter type
				for (int i = 0, imax = mParameters.Length; i < imax; ++i)
					mParameters[i].expectedType = mParameterInfos[i].ParameterType;
			}
		}
#endif // REFLECTION_SUPPORT
	}
Esempio n. 11
0
        public void Load(MethodInfo executeMethod, byte[] queryData, Type[] earlyBoundTypes)
        {
            Reset();

            if (executeMethod == null)
                throw new ArgumentNullException(nameof(executeMethod));

            if (queryData == null)
                throw new ArgumentNullException(nameof(queryData));


            DynamicMethod dm = executeMethod as DynamicMethod;
            Delegate delExec = (dm != null) ? dm.CreateDelegate(typeof(ExecuteDelegate)) : executeMethod.CreateDelegate(typeof(ExecuteDelegate));
            _command = new XmlILCommand((ExecuteDelegate)delExec, new XmlQueryStaticData(queryData, earlyBoundTypes));
            _outputSettings = _command.StaticData.DefaultWriterSettings;
        }
Esempio n. 12
0
 public InvokableCall(object target, MethodInfo theFunction) : base(target, theFunction)
 {
     this.Delegate = (UnityAction) System.Delegate.Combine(this.Delegate, (UnityAction) theFunction.CreateDelegate(typeof(UnityAction), target));
 }
Esempio n. 13
0
        public void RegisterNonShared(MethodInfo method, object container, params MessageHandlerAttribute[] attributes)
        {
            if (method == null) throw new ArgumentNullException("method");
            if (attributes == null || attributes.Length == 0)
                return;

            var parameters = method.GetParameters();

            if (parameters.Length != 2 ||
                !parameters[1].ParameterType.IsSubclassOf(typeof(Message)))
            {
                throw new ArgumentException(string.Format("Method handler {0} has incorrect parameters. Right definition is Handler(object, Message)", method));
            }

            if (!method.IsStatic && container == null)
                throw new ArgumentException("You must give an object container if the method is static");

            Action<object, object, Message> handlerDelegate;
            try
            {
                handlerDelegate = (Action<object, object, Message>)method.CreateDelegate(typeof(object), typeof(Message));
            }
            catch (Exception)
            {
                throw new ArgumentException(string.Format("Method handler {0} has incorrect parameters. Right definition is Handler(object Message)", method));
            }

            foreach (var attribute in attributes)
            {
                RegisterNonShared(attribute.MessageType, method.DeclaringType, attribute, handlerDelegate, parameters[0].ParameterType, method.IsStatic ? null : container);
            }
        }
Esempio n. 14
0
    private bool bindToEventField( MethodInfo eventHandler )
    {
        eventField = getField( sourceComponent, DataSource.MemberName );
        if( eventField == null )
        {
            return false;
        }

        try
        {

            var eventMethod = eventField.FieldType.GetMethod( "Invoke" );
            var eventParams = eventMethod.GetParameters();
            var handlerParams = eventHandler.GetParameters();

            var needProxyDelegate =
                ( eventParams.Length != handlerParams.Length ) ||
                ( eventMethod.ReturnType != eventHandler.ReturnType );

            if( !needProxyDelegate )
            {
        #if !UNITY_EDITOR && UNITY_METRO
                eventDelegate = eventHandler.CreateDelegate( eventField.FieldType, targetComponent );
        #else
                eventDelegate = Delegate.CreateDelegate( eventField.FieldType, targetComponent, eventHandler, true );
        #endif
            }
            else
            {
                eventDelegate = createEventProxyDelegate( targetComponent, eventField.FieldType, eventParams, eventHandler );
            }

            var combinedDelegate = Delegate.Combine( eventDelegate, (Delegate)eventField.GetValue( sourceComponent ) );
            eventField.SetValue( sourceComponent, combinedDelegate );

        }
        catch( Exception err )
        {
            this.enabled = false;
            var errMessage = string.Format( "Event binding failed - Failed to create event handler for {0} ({1}) - {2}", DataSource, eventHandler, err.ToString() );
            Debug.LogError( errMessage, this );
            return false;
        }

        return true;
    }
Esempio n. 15
0
        /// <summary>
        /// Creates a delegate for the specified method and target.
        /// </summary>
        /// <param name="delegateType">Type of the delegate.</param>
        /// <param name="target">The target. If <c>null</c>, the method will be assumed static.</param>
        /// <param name="methodInfo">The method info.</param>
        /// <returns>The delegate.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="delegateType"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="methodInfo"/> is <c>null</c>.</exception>
        public static Delegate CreateDelegate(Type delegateType, object target, MethodInfo methodInfo)
        {
            Argument.IsNotNull("delegateType", delegateType);
            Argument.IsNotNull("methodInfo", methodInfo);

#if NETFX_CORE || PCL
            return methodInfo.CreateDelegate(delegateType, target);
#else
            return Delegate.CreateDelegate(delegateType, target, methodInfo);
#endif
        }
 public static Delegate CreateDelegate(Type type, object target, MethodInfo method)
 {
     return method.CreateDelegate(type, target);
 }
Esempio n. 17
0
	/// <summary>
	/// Cache the callback and create the list of the necessary parameters.
	/// </summary>

	void Cache ()
	{
		mCached = true;
		if (mRawDelegate) return;

#if REFLECTION_SUPPORT
		if (mCachedCallback == null || (mCachedCallback.Target as MonoBehaviour) != mTarget || GetMethodName(mCachedCallback) != mMethodName)
		{
			if (mTarget != null && !string.IsNullOrEmpty(mMethodName))
			{
				System.Type type = mTarget.GetType();

				try
				{
#if NETFX_CORE
					// we can't use this since we don't seem to have the correct parameter type list yet
					// mMethod = type.GetRuntimeMethod(mMethodName, (from p in mParameters select p.type).ToArray());

					mMethod = (from m in type.GetRuntimeMethods() where m.Name == mMethodName && !m.IsStatic select m).FirstOrDefault();
#else
					for (mMethod = null; ; )
					{
						mMethod = type.GetMethod(mMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
						if (mMethod != null) break;
						type = type.BaseType;
						if (type == null) break;
					}
#endif
				}
				catch (System.Exception ex)
				{
					Debug.LogError("Failed to bind " + type + "." + mMethodName + "\n" +  ex.Message);
					return;
				}

				if (mMethod == null)
				{
					Debug.LogError("Could not find method '" + mMethodName + "' on " + mTarget.GetType(), mTarget);
					return;
				}
				
				if (mMethod.ReturnType != typeof(void))
				{
					Debug.LogError(mTarget.GetType() + "." + mMethodName + " must have a 'void' return type.", mTarget);
					return;
				}

				// Get the list of expected parameters
				ParameterInfo[] info = mMethod.GetParameters();

				if (info.Length == 0)
				{
					// No parameters means we can create a simple delegate for it, optimizing the call
#if NETFX_CORE
					mCachedCallback = (Callback)mMethod.CreateDelegate(typeof(Callback), mTarget);
#else
					mCachedCallback = (Callback)System.Delegate.CreateDelegate(typeof(Callback), mTarget, mMethodName);
#endif

					mArgs = null;
					mParameters = null;
					return;
				}
				else mCachedCallback = null;

				// Allocate the initial list of parameters
				if (mParameters == null || mParameters.Length != info.Length)
				{
					mParameters = new Parameter[info.Length];
					for (int i = 0, imax = mParameters.Length; i < imax; ++i)
						mParameters[i] = new Parameter();
				}

				// Save the parameter type
				for (int i = 0, imax = mParameters.Length; i < imax; ++i)
					mParameters[i].expectedType = info[i].ParameterType;
			}
		}
#endif
	}
Esempio n. 18
0
        private static Delegate CreateDelegate(MethodInfo method, object target)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }

            return method.CreateDelegate(Expression.GetDelegateType(
                (from parameter in method.GetParameters() select parameter.ParameterType)
                    .Concat(new[] {method.ReturnType})
                    .ToArray()), target);
        }
Esempio n. 19
0
        public void Load(MethodInfo executeMethod, byte[] queryData, Type[] earlyBoundTypes)
        {
            Reset();

            if (executeMethod == null)
                throw new ArgumentNullException(nameof(executeMethod));

            if (queryData == null)
                throw new ArgumentNullException(nameof(queryData));

            // earlyBoundTypes may be null

            /*if (!System.Xml.XmlConfiguration.XsltConfigSection.EnableMemberAccessForXslCompiledTransform)
            {
                // make sure we have permission to create the delegate if the type is not visible.
                // If the declaring type is null we cannot check for visibility.
                // NOTE: a DynamicMethod will always have a DeclaringType == null. DynamicMethods will do demand on their own if skipVisibility is true. 
                if (executeMethod.DeclaringType != null && !executeMethod.DeclaringType.IsVisible)
                {
                    new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
                }
            }*/

            DynamicMethod dm = executeMethod as DynamicMethod;
            Delegate delExec = (dm != null) ? dm.CreateDelegate(typeof(ExecuteDelegate)) : executeMethod.CreateDelegate(typeof(ExecuteDelegate));
            _command = new XmlILCommand((ExecuteDelegate)delExec, new XmlQueryStaticData(queryData, earlyBoundTypes));
            _outputSettings = _command.StaticData.DefaultWriterSettings;
        }
Esempio n. 20
0
    private bool bindToEventProperty( MethodInfo eventHandler )
    {
        eventInfo = sourceComponent.GetType().GetEvent( DataSource.MemberName );
        if( eventInfo == null )
            return false;

        try
        {

            var eventDelegateType = eventInfo.EventHandlerType;
            var addMethod = eventInfo.GetAddMethod();

            var eventMethod = eventDelegateType.GetMethod( "Invoke" );
            var eventParams = eventMethod.GetParameters();
            var handlerParams = eventHandler.GetParameters();

            var needProxyDelegate =
                ( eventParams.Length != handlerParams.Length ) ||
                ( eventMethod.ReturnType != eventHandler.ReturnType );

            if( !needProxyDelegate )
            {
        #if !UNITY_EDITOR && UNITY_METRO
                eventDelegate = eventHandler.CreateDelegate( eventDelegateType, targetComponent );
        #else
                eventDelegate = Delegate.CreateDelegate( eventDelegateType, targetComponent, eventHandler, true );
        #endif

            }
            else
            {
                eventDelegate = createEventProxyDelegate( targetComponent, eventDelegateType, eventParams, eventHandler );
            }

            addMethod.Invoke( DataSource.Component, new object[] { eventDelegate } );

        }
        catch( Exception err )
        {
            this.enabled = false;
            var errMessage = string.Format( "Event binding failed - Failed to create event handler for {0} ({1}) - {2}", DataSource, eventHandler, err.ToString() );
            Debug.LogError( errMessage, this );
            return false;
        }

        return true;
    }