Skip to content

Instantly share code, notes, and snippets.

@tana
Created January 12, 2021 04:51
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 tana/465af214d7cf463bbc364c4048cf1d0a to your computer and use it in GitHub Desktop.
Save tana/465af214d7cf463bbc364c4048cf1d0a to your computer and use it in GitHub Desktop.
IL shift amount test
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace EmitTest
{
class EmitTest
{
static void Main(string[] args)
{
var assembly = AssemblyBuilder.DefineDynamicAssembly(
new AssemblyName("TestAssembly"),
AssemblyBuilderAccess.Run
);
var module = assembly.DefineDynamicModule("TestModule");
var cls = module.DefineType("TestClass", TypeAttributes.Public | TypeAttributes.Class);
{
// int64 TestNoConv(int64 a, int64 b);
var method = cls.DefineMethod(
"TestNoConv",
MethodAttributes.Public | MethodAttributes.Static,
typeof(long),
new Type[] { typeof(long), typeof(long) }
);
var il = method.GetILGenerator();
// return a << b;
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Shl);
il.Emit(OpCodes.Ret);
}
{
// int64 TestInt32(int64 a, int64 b);
var method = cls.DefineMethod(
"TestInt32",
MethodAttributes.Public | MethodAttributes.Static,
typeof(long),
new Type[] { typeof(long), typeof(long) }
);
var il = method.GetILGenerator();
// return a << (int32)b;
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Conv_I4);
il.Emit(OpCodes.Shl);
il.Emit(OpCodes.Ret);
}
{
// int64 TestNativeInt(int64 a, int64 b);
var method = cls.DefineMethod(
"TestNativeInt",
MethodAttributes.Public | MethodAttributes.Static,
typeof(long),
new Type[] { typeof(long), typeof(long) }
);
var il = method.GetILGenerator();
// return a << (native int)b;
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Shl);
il.Emit(OpCodes.Ret);
}
var type = cls.CreateType();
Test(type, "TestNoConv");
Test(type, "TestInt32");
Test(type, "TestNativeInt");
}
static void Test(Type type, string name)
{
Console.Write(name + ": ");
try
{
var m = type.GetMethod(name);
Console.WriteLine(m.Invoke(null, new object[] { (long)10, (long)1 }));
}
catch (Exception)
{
Console.WriteLine("Exception occured!");
}
}
}
}
TestNoConv: Exception occured!
TestInt32: 20
TestNativeInt: 20
TestNoConv: 20
TestInt32: 20
TestNativeInt: 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment