Metal programming technology and dynamic compilation

xiaoxiao2021-03-06  53

Original: http://www.cnblogs.com/windsails/archive/2004/09/07/40754.aspx

Metal programming technology and dynamic compilation

What is meta programming?

The function of the time-running dynamically created type is called metabographs. (This is the definition of .NET environment programming panorama)

From learning UML, you know Meta-, then later, MOF (MetaObjectFacility) is more fascinated by Meta-. Meta- ... ... I'm very important to understand the Meta things for you to know about a Framework. Regardless of any Framework, there is a good multi-diverse data in .NET as a Framework naturally, and we can write a flexible application technology in the application, you can definitely make our program more flexible and efficient. Even self-generation.

The following figure shows the class-related classes related to the .NET Framework: For example, the following example directly generates a DLL and calls the dynamic method in this DLL:

Using

System;

Using

System.Reflection;

Using

System.Reflection.emit;

Using

System.Threading;

Namespace

Testmetaprog

{///// Class1 summary description. /// Class Class1 {/// // The primary invested point of the application. /// [static "static void main (string [] args) {// // Todo: Add code here to start the application // assemblyname An = new assemblyName (); an.Name =" mymetaprog "; askEMBLYBUILDER . ab = Thread.GetDomain () DefineDynamicAssembly (an, AssemblyBuilderAccess.RunAndSave); ModuleBuilder mb = ab.DefineDynamicModule ( "MetaProgModule", "myMetaProg.dll", true); TypeBuilder tb = mb.DefineType ( "MetaProg.NewType", TypeAttributes.Public); MethodBuilder m = tb.DefineMethod ( "MetaProgMethod", MethodAttributes.Public, null, null); CreateMethodBody (m); tb.CreateType (); ab.Save ( "myMetaProg.dll"); Type t = Type.GetType ( "MetaProg.NewType, myMetaProg", true); Object o = Activator.CreateInstance (t); MethodInfo myMethod = t.GetMethod ( "MetaProgMethod"); myMethod.Invoke (o, null); myMethod = t. GetMethod ("toString"); Console.Writeline (MyMethod.invoke (O, NULL);} Private Static Void CreateMethodBody (Methodbuilder M) {ilgenerator il = m.getilgenerator (); il.emitwriteline ("Output a new type:"); il.emit (OPCODES.RET);}}} Generate: Use ILDASM to see the generation DLL, the discovery is indeed a valid CLR file: where the MetAProgMethod method corresponds to the following:

Thinking: Yuan programming seems to be able to directly generate the compiled effect file, and Microsoft.csharp.compiler has a compilation class.

You can compile the input CS format files, what is the difference between the two? That kind of better?

download

Example code

转载请注明原文地址:https://www.9cbs.com/read-114879.html

New Post(0)