Skip to content

Instantly share code, notes, and snippets.

@bleis-tift
Last active October 19, 2015 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bleis-tift/3ed75a539f2b9612cc1b to your computer and use it in GitHub Desktop.
Save bleis-tift/3ed75a539f2b9612cc1b to your computer and use it in GitHub Desktop.
ldc.i4.sで負数をintのままemitすると不正なILが生成される
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