473,626 Members | 3,210 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 PrintTemplateOn e()
{
Console.WriteLi ne("I'm the method of template #1");
}
}

class TemplateTwo
{
public void PrintTemplateTw o()
{
Console.WriteLi ne("I'm the method of template #2");
}
}

public interface IOneAndTwo
{
void PrintTemplateOn e();
void PrintTemplateTw o();
}

class Program
{
static void Main(string[] args)
{
AssemblyName newAssemName = new
AssemblyName("F romTwoTemplates ");
AssemblyBuilder asmBuilder =
Thread.GetDomai n().DefineDynam icAssembly(newA ssemName,
AssemblyBuilder Access.Run);
ModuleBuilder moduleBuilder =
asmBuilder.Defi neDynamicModule ("FromTwoTempla tes");
TypeBuilder newType =
moduleBuilder.D efineType("TwoT emplatesMethods ",
TypeAttributes. Class | TypeAttributes. Public);
newType.AddInte rfaceImplementa tion(typeof(IOn eAndTwo));

MethodBuilder method1Builder =
newType.DefineM ethod(typeof(IO neAndTwo).GetMe thods()[0].Name,
MethodAttribute s.Public | MethodAttribute s.Virtual,
typeof(IOneAndT wo).GetMethods( )[0].ReturnType,

GetParameterTyp es(typeof(IOneA ndTwo).GetMetho ds()[0].GetParameters( )));

MethodBody mb =
typeof(Template One).GetMethods ()[0].GetMethodBody( );
method1Builder. CreateMethodBod y(mb.GetILAsByt eArray(),
mb.GetILAsByteA rray().Length);

MethodBuilder method2Builder =
newType.DefineM ethod(typeof(IO neAndTwo).GetMe thods()[1].Name,
MethodAttribute s.Public | MethodAttribute s.Virtual,
typeof(IOneAndT wo).GetMethods( )[1].ReturnType,

GetParameterTyp es(typeof(IOneA ndTwo).GetMetho ds()[1].GetParameters( )));

mb = typeof(Template Two).GetMethods ()[0].GetMethodBody( );
method2Builder. CreateMethodBod y(mb.GetILAsByt eArray(),
mb.GetILAsByteA rray().Length);

newType.DefineM ethodOverride(m ethod1Builder,
typeof(IOneAndT wo).GetMethods( )[0]);
newType.DefineM ethodOverride(m ethod2Builder,
typeof(IOneAndT wo).GetMethods( )[1]);

Type created = newType.CreateT ype();

IOneAndTwo oneTwo1 = asmBuilder.Crea teInstance(newT ype.Name)
as IOneAndTwo;

Console.WriteLi ne("Copied methods:");
oneTwo1.PrintTe mplateOne();
oneTwo1.PrintTe mplateTwo();
Console.ReadKey ();
}

private static Type[] GetParameterTyp es(ParameterInf o[]
parameterInfo)
{
Type[] paramTypes = new Type[parameterInfo.L ength];
for (int i = 0; i < parameterInfo.L ength; i++)
{
paramTypes[i] = parameterInfo[i].ParameterType;
}
return paramTypes;
}
}

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

System.BadImage FormatException was unhandled
Message="Bad method token."
Source="FromTwo Templates"
StackTrace:
at TwoTemplatesMet hods.PrintTempl ateOne()
at ReflectionTest. Program.Main(St ring[] args) in
D:\Documents\Vi sual Studio
2005\Projects\R eflectionTest\R eflectionTest\P rogram.cs:line 50
at System.AppDomai n.nExecuteAssem bly(Assembly assembly, String[]
args)
at System.AppDomai n.ExecuteAssemb ly(String assemblyFile,
Evidence assemblySecurit y, String[] args)
at
Microsoft.Visua lStudio.Hosting Process.HostPro c.RunUsersAssem bly()
at System.Threadin g.ThreadHelper. ThreadStart_Con text(Object
state)
at System.Threadin g.ExecutionCont ext.Run(Executi onContext
executionContex t, ContextCallback callback, Object state)
at System.Threadin g.ThreadHelper. ThreadStart()

Any advices?

Thanks in advance
Mick

Oct 19 '06 #1
0 1396

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

Similar topics

0
2184
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 Reflection.Emit which inherits from the object needed Person p = (Person)ProxyBuilder.Construct(typeof(Person));
0
8435
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. xxx======================================================================
7
9957
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 method. The method could look like this: public void myDynamicMethod(Type type){ //.....do something with the Type passed in....... }
3
2517
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 something that If done with Reflection.Emit will be a lot faster or something sensible. I will really appreciate your help. Thanks : John Arthur
3
3040
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
3631
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
1649
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: //************************************************************** ..method public hidebysig instance class System.Data.SqlClient.SqlCommand Format1(class Delta.DictionaryDispatch dispatch) cil managed { .custom instance void Delta.DispatchNameAttribute::.ctor(string) = ( 01 00 0B 43 4F 4D 4D 41 4E 44 5F 4F...
5
1859
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 author of an application, I already know the metadata about my classes - I wrote them. And even if I did not - Let's say I buy a 3rd party class lib, it will be documented for me with that lib. If I am part of a dev team, the same is true - If...
9
4162
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 System.Reflection. Regards, Michael
0
1654
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 = typeof(List<>).MakeGenericType(typeof(myClass)).GetMethod("AddRange", BindingFlags.Instance | BindingFlags.Public, null, new Type { typeof(IEnumerable<>).MakeGenericType(typeof(myClass)) }, null)); and then the implementation
0
8265
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8705
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8637
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8364
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8504
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7193
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5574
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2625
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1808
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.