Last active
October 19, 2015 08:41
-
-
Save bleis-tift/3ed75a539f2b9612cc1b to your computer and use it in GitHub Desktop.
ldc.i4.sで負数をintのままemitすると不正なILが生成される
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Reflection; | |
using System.Reflection.Emit; | |
namespace SampleApplication | |
{ | |
public interface I | |
{ | |
int F(); | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("test"), AssemblyBuilderAccess.RunAndSave); | |
var mod = asm.DefineDynamicModule("test", "test.dll", true); | |
var typ = mod.DefineType("Sample", TypeAttributes.Public, typeof(object), new[] { typeof(I) }); | |
var m = typ.DefineMethod("F", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard, typeof(int), new Type[0]); | |
var gen = m.GetILGenerator(); | |
//gen.Emit(OpCodes.Ldc_I4_S, -120); // 120だとOK | |
gen.Emit(OpCodes.Ldc_I4_S, (sbyte)-120); // 上だとintのオーバーロードが選択されるため、sbyteに変換する必要があった | |
gen.Emit(OpCodes.Ret); | |
var x = Activator.CreateInstance(typ.CreateType()) as I; | |
asm.Save("test"); | |
Console.WriteLine(x.F()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment