메서드를 클래스에서 IL 코드로 변환 한 다음 호출하여 실행하고 싶습니다. 내가 따르는 예는 msdn : https://msdn.microsoft.com/en-us/library/system.reflection.emit.methodbuilder.createmethodbody(v=vs.110).aspx입니다.클래스 메서드를 IL로 변환하여 런타임에 실행하십시오.
정확히 내가 원하는 것을 보여줍니다, 내 문제는 클래스 메서드에서 ILcodes 생성하는 것입니다.
:public class MethodBodyDemo
{
public int Add(int x, int y)
{
return x + y;
}
}
내가 바이트 배열을 채우기 위해 다음 호출을 시도 :
그래서 기본적으로 내가 예를 들어 클래스에 정의 된 방법에서 다음
byte[] ILcodes = new byte[] {
0x02, /* 02h is the opcode for ldarg.0 */
0x03, /* 03h is the opcode for ldarg.1 */
0x58, /* 58h is the opcode for add */
0x2A /* 2Ah is the opcode for ret */
};
를 작성해야
var ILcodes = typeof(MethodBodyDemo).GetMethod("Add").GetMethodBody().GetILAsByteArray();
다음은 내가 만드는 예제이지만 예외를 제공합니다. "공용 언어 런타임에서 잘못된 프로그램을 발견했습니다."
public class MethodBodyDemo
{
public int Add(int x, int y)
{
return x + y;
}
// This class will demonstrate how to create a method body using
// the MethodBuilder.CreateMethodBody(byte[], int) method.
public static Type BuildDynType()
{
Type addType = null;
AppDomain currentDom = Thread.GetDomain();
AssemblyName myAsmName = new AssemblyName();
myAsmName.Name = "MyDynamicAssembly";
AssemblyBuilder myAsmBldr = currentDom.DefineDynamicAssembly(
myAsmName,
AssemblyBuilderAccess.RunAndSave);
// The dynamic assembly space has been created. Next, create a module
// within it. The type Point will be reflected into this module.
ModuleBuilder myModuleBldr = myAsmBldr.DefineDynamicModule("MyModule");
TypeBuilder myTypeBldr = myModuleBldr.DefineType("Adder");
MethodBuilder myMthdBldr = myTypeBldr.DefineMethod("Add",
MethodAttributes.Public |
MethodAttributes.Static,
typeof(int),
new Type[]
{typeof(int), typeof(int)});
// Build the array of Bytes holding the MSIL instructions.
// byte[] ILcodes = new byte[] {
// 0x02, /* 02h is the opcode for ldarg.0 */
// 0x03, /* 03h is the opcode for ldarg.1 */
// 0x58, /* 58h is the opcode for add */
// 0x2A /* 2Ah is the opcode for ret */
//};
var ILcodes = typeof(MethodBodyDemo).GetMethod("Add").GetMethodBody().GetILAsByteArray();
myMthdBldr.CreateMethodBody(ILcodes, ILcodes.Length);
addType = myTypeBldr.CreateType();
return addType;
}
public static void TestExecMethod()
{
Type myType = BuildDynType();
Console.WriteLine("---");
Console.Write("Enter the first integer to add: ");
int aVal = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the second integer to add: ");
int bVal = Convert.ToInt32(Console.ReadLine());
object adderInst = Activator.CreateInstance(myType, new object[0]);
Console.WriteLine("The value of adding {0} to {1} is: {2}.",
aVal, bVal,
myType.InvokeMember("Add",
BindingFlags.InvokeMethod,
null,
adderInst,
new object[] { aVal, bVal }));
}
}
호출하여 실행합니다
MethodBodyDemo.TestExecMethod();
어떤 도움을 주 시겠어요?
호기심에서 벗어나, 결국 무엇을하려합니까?:) 직접적으로 (또는 간접적으로 리플렉션을 사용하여) 메소드를 호출하거나 'System.Reflection.Emit.ILGenerator'를 사용하여 명령어를 작성하는 것이 잘못된 것은 무엇입니까? – Caramiriel
저는 약간 혼란 스럽습니다 - 기본적으로 동적으로 새 메서드를 객체에 추가하고 객체를 호출하려고합니까? – EJoshuaS
내가 찾고있는 것은 메서드를 다른 시스템으로 보내고 해당 시스템이이 메서드를 실행하지만 다른 시스템은 사용중인 라이브러리에 대해 알지 못합니다. 위 코드는 ILcode를 채우는 방법입니다. –