private void CopyFrom([NotNull] MethodDefinition fromMethod) { if (fromMethod.Body.HasExceptionHandlers) { throw new NotSupportedException("Try-catch-finally construction are not supported yet."); } foreach (var instruction in fromMethod.Body.Instructions) { _labels.Add(instruction.Offset, _ilGenerator.DefineLabel()); } foreach (var variable in fromMethod.Body.Variables) { _variables.Add(variable.Index, _ilGenerator.DeclareLocal(_typeMapper.GetRuntimeType(variable.VariableType), variable.IsPinned)); } foreach (var instruction in fromMethod.Body.Instructions) { var currentLabel = _labels[instruction.Offset]; _ilGenerator.MarkLabel(currentLabel); EmitInstruction(instruction); } }
public static DynamicMethod CopyToDynamicMethod([NotNull] MethodDefinition method) { if (method == null) { throw new ArgumentNullException(nameof(method)); } var typeMapper = new TypeReferenceMapper(); var methodMapper = new MethodReferenceMapper(typeMapper); var dynamicMethod = new DynamicMethod( method.Name, typeMapper.GetRuntimeType(method.ReturnType), method.Parameters.Select(param => typeMapper.GetRuntimeType(param.ParameterType)).ToArray(), true); dynamicMethod.InitLocals = method.Body.InitLocals; var ilGenerator = dynamicMethod.GetILGenerator(); var copier = new ILCopier(ilGenerator, typeMapper, methodMapper); copier.CopyFrom(method); return(dynamicMethod); }
public MethodInfo GetMethod(MethodReference methodReference) { var referenceSignature = Signature.Create(methodReference); var declaringType = _typeMapper.GetRuntimeType(methodReference.DeclaringType); var methods = declaringType.GetMembers() .OfType <MethodInfo>() .Where(methodInfo => methodInfo.Name == methodReference.Name && methodInfo.GetParameters().Length == methodReference.Parameters.Count); foreach (var methodInfo in methods) { var methodSignature = Signature.Create(methodInfo); if (Equals(referenceSignature, methodSignature)) { if (methodInfo.IsGenericMethodDefinition) { var genericMethod = (GenericInstanceMethod)methodReference; var genericArguments = genericMethod.GenericArguments .Select(item => _typeMapper.GetRuntimeType(item, methodReference.DeclaringType)) .ToArray(); return(methodInfo.MakeGenericMethod(genericArguments)); } return(methodInfo); } } throw new NotSupportedException(string.Format( CultureInfo.InvariantCulture, "Method not found:\r\n{0}\r\nExisting methods:\r\n{1}", methodReference.ToString(), string.Join("\r\n", methods))); }