code_junkie

Is it possible to indirectly load a value type on the stack

Nov 10th, 2011
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. var local = il.DeclareLocal(typeof(Nullable<int>));
  2. il.Emit(OpCodes.Stloc, local);
  3. il.Emit(OpCodes.Ldloca, local);
  4. var method = typeof(Nullable<int>).GetMethod("get_HasValue");
  5. il.EmitCall(OpCodes.Call, method, null);
  6.  
  7. il.Emit(/* not sure */);
  8. var method = typeof(Nullable<int>).GetMethod("get_HasValue");
  9. il.EmitCall(OpCodes.Call, method, null);
  10.  
  11. var m = new DynamicMethod("M", typeof(bool), Type.EmptyTypes);
  12. var il = m.GetILGenerator();
  13. var ctor = typeof(Nullable<int>).GetConstructor(new[] { typeof(int) });
  14. il.Emit(OpCodes.Ldc_I4_6);
  15. il.Emit(OpCodes.Newobj, ctor);
  16. //var local = il.DeclareLocal(typeof(Nullable<int>));
  17. //il.Emit(OpCodes.Stloc, local);
  18. //il.Emit(OpCodes.Ldloca, local);
  19. var getValue = typeof(Nullable<int>).GetMethod("get_HasValue");
  20. il.Emit(OpCodes.Call, getValue);
  21. il.Emit(OpCodes.Ret);
  22. Console.WriteLine(m.Invoke(null, null));
  23.  
  24. DynamicMethod method = new DynamicMethod("M", typeof(bool), Type.EmptyTypes);
  25. ILGenerator il = method.GetILGenerator();
  26. Type nullable = typeof(Nullable<int>);
  27. ConstructorInfo ctor = nullable.GetConstructor(new Type[] { typeof(int) });
  28. MethodInfo getValue = nullable.GetProperty("HasValue").GetGetMethod();
  29. LocalBuilder value = il.DeclareLocal(nullable);
  30.  
  31. // load the variable to assign the value from the ctor to
  32. il.Emit(OpCodes.Ldloca_S, value);
  33. // load constructor args
  34. il.Emit(OpCodes.Ldc_I4_6);
  35. il.Emit(OpCodes.Call, ctor);
  36. il.Emit(OpCodes.Ldloca_S, value);
  37.  
  38. il.Emit(OpCodes.Call, getValue);
  39. il.Emit(OpCodes.Ret);
  40. Console.WriteLine(method.Invoke(null, null));
Add Comment
Please, Sign In to add comment