/src/LinFu.AOP/Emitters/SaveReturnValue.cs

http://github.com/philiplaureano/LinFu · C# · 46 lines · 27 code · 7 blank · 12 comment · 6 complexity · 174b513676503edf25a9ad7f37b4489c MD5 · raw file

  1. using LinFu.AOP.Cecil.Interfaces;
  2. using LinFu.Reflection.Emit;
  3. using Mono.Cecil;
  4. using Mono.Cecil.Cil;
  5. namespace LinFu.AOP.Cecil
  6. {
  7. /// <summary>
  8. /// Represents an instruction emitter that saves the return value from a given method call.
  9. /// </summary>
  10. public class SaveReturnValue : IInstructionEmitter
  11. {
  12. private readonly TypeReference _returnType;
  13. private readonly VariableDefinition _returnValue;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="SaveReturnValue" /> class.
  16. /// </summary>
  17. /// <param name="returnType">The return type.</param>
  18. /// <param name="returnValue">The return value.</param>
  19. public SaveReturnValue(TypeReference returnType, VariableDefinition returnValue)
  20. {
  21. _returnType = returnType;
  22. _returnValue = returnValue;
  23. }
  24. /// <summary>
  25. /// Saves the return value from a given method call.
  26. /// </summary>
  27. /// <param name="IL">The <see cref="ILProcessor" /> pointing to the target method body.</param>
  28. public void Emit(ILProcessor IL)
  29. {
  30. var module = IL.Body.Method.DeclaringType.Module;
  31. var voidType = module.ImportType(typeof(void));
  32. var returnTypeIsValueType = _returnType != voidType && _returnType.IsValueType;
  33. if (_returnType is GenericParameter || returnTypeIsValueType)
  34. IL.Create(OpCodes.Box, _returnType);
  35. if (_returnType != voidType)
  36. IL.Create(OpCodes.Stloc, _returnValue);
  37. }
  38. }
  39. }