473,394 Members | 1,787 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Reflection.Emit usage

Hello all!
Can anybody provide a good example for the Reflectio.Emitl namespace
usage? The problem I'm trying to solve is copying the method body from
existing class to newly created one.
Below is the code targeting .Net 2.0 , that I'm trying to use without
success:

class TemplateOne
{
public void PrintTemplateOne()
{
Console.WriteLine("I'm the method of template #1");
}
}

class TemplateTwo
{
public void PrintTemplateTwo()
{
Console.WriteLine("I'm the method of template #2");
}
}

public interface IOneAndTwo
{
void PrintTemplateOne();
void PrintTemplateTwo();
}

class Program
{
static void Main(string[] args)
{
AssemblyName newAssemName = new
AssemblyName("FromTwoTemplates");
AssemblyBuilder asmBuilder =
Thread.GetDomain().DefineDynamicAssembly(newAssemN ame,
AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder =
asmBuilder.DefineDynamicModule("FromTwoTemplates") ;
TypeBuilder newType =
moduleBuilder.DefineType("TwoTemplatesMethods",
TypeAttributes.Class | TypeAttributes.Public);
newType.AddInterfaceImplementation(typeof(IOneAndT wo));

MethodBuilder method1Builder =
newType.DefineMethod(typeof(IOneAndTwo).GetMethods ()[0].Name,
MethodAttributes.Public | MethodAttributes.Virtual,
typeof(IOneAndTwo).GetMethods()[0].ReturnType,

GetParameterTypes(typeof(IOneAndTwo).GetMethods()[0].GetParameters()));

MethodBody mb =
typeof(TemplateOne).GetMethods()[0].GetMethodBody();
method1Builder.CreateMethodBody(mb.GetILAsByteArra y(),
mb.GetILAsByteArray().Length);

MethodBuilder method2Builder =
newType.DefineMethod(typeof(IOneAndTwo).GetMethods ()[1].Name,
MethodAttributes.Public | MethodAttributes.Virtual,
typeof(IOneAndTwo).GetMethods()[1].ReturnType,

GetParameterTypes(typeof(IOneAndTwo).GetMethods()[1].GetParameters()));

mb = typeof(TemplateTwo).GetMethods()[0].GetMethodBody();
method2Builder.CreateMethodBody(mb.GetILAsByteArra y(),
mb.GetILAsByteArray().Length);

newType.DefineMethodOverride(method1Builder,
typeof(IOneAndTwo).GetMethods()[0]);
newType.DefineMethodOverride(method2Builder,
typeof(IOneAndTwo).GetMethods()[1]);

Type created = newType.CreateType();

IOneAndTwo oneTwo1 = asmBuilder.CreateInstance(newType.Name)
as IOneAndTwo;

Console.WriteLine("Copied methods:");
oneTwo1.PrintTemplateOne();
oneTwo1.PrintTemplateTwo();
Console.ReadKey();
}

private static Type[] GetParameterTypes(ParameterInfo[]
parameterInfo)
{
Type[] paramTypes = new Type[parameterInfo.Length];
for (int i = 0; i < parameterInfo.Length; i++)
{
paramTypes[i] = parameterInfo[i].ParameterType;
}
return paramTypes;
}
}

When it comes to the first method invocation (PrintTemplateOne) I get
the following exception:

System.BadImageFormatException was unhandled
Message="Bad method token."
Source="FromTwoTemplates"
StackTrace:
at TwoTemplatesMethods.PrintTemplateOne()
at ReflectionTest.Program.Main(String[] args) in
D:\Documents\Visual Studio
2005\Projects\ReflectionTest\ReflectionTest\Progra m.cs:line 50
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[]
args)
at System.AppDomain.ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity, String[] args)
at
Microsoft.VisualStudio.HostingProcess.HostProc.Run UsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context( Object
state)
at System.Threading.ExecutionContext.Run(ExecutionCon text
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

Any advices?

Thanks in advance
Mick

Oct 19 '06 #1
0 1382

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Nigel Sampson | last post by:
ey all, I'm in the process of creating a method of tracking whenever an objects properties are changed. Since its not possible to alter existing types I decided to used a proxy generated using...
0
by: samlee | last post by:
Hi All, I'm learning how to write C# using reflection, but don't know how to code using reflection this.Controls.Add(this.label1); Could anyone help, Thank in advance. ...
7
by: Mark Miller | last post by:
I am using Reflection.Emit to dynamically build a class. A method of the class to be built requires a Parameter of type "Type". But I don't know how to use Emit to pass a call of "typeof()" to the...
3
by: John Arthur | last post by:
Hi, I am reading about Reflection.Emit and I can't really imagine a real situation where I can use this. Can someone give me an example that can't be done without Reflection or an example of...
3
by: ayende | last post by:
How do I use Reflection.Emit to produce code similar to this? public void bar<T>() { } public void foo<J>() { bar<J>(); }
2
by: Luis Arvayo | last post by:
Hi, In c#, I need to dynamically create types at runtime that will consist of the following: - inherits from a given interface - will have a constructor with an int argument
2
by: allfyre | last post by:
Ok, to make a long story short, I'm Emitting some MSIL from a c# application. I know that THIS is the MSIL I want to be emitting: //**************************************************************...
5
by: heddy | last post by:
I understand that reflection allows me to discover the metadata of a class at runtime (properties, methods etc). What I don't understand is where this is useful. For example: If I am the sole...
9
by: Michael Sander | last post by:
Hello ng, anyone knowns how to add a reference to an assembly to System.Reflection.AssemblyBuilder? In System.Web.Compilation.AssemblyBuilder is a function like AddAssemblyReference, but not in...
0
by: =?Utf-8?B?QXJ0dXJvIE1hcnRpbmV6?= | last post by:
I've been looking everywhere on how to call AddRange Method of a List<myClassfield in Reflection.Emit My code goes like this MethodInfo method =...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.