473,770 Members | 1,661 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating interface type at run-time using code emitting

1 New Member
I need to create interface "on-the-fly" so it "reflects" some class (mainly it's properties). Here's how I do this:

Expand|Select|Wrap|Line Numbers
  1.     public class Transformer
  2.     {
  3.         private const TypeAttributes INTERFACE_TYPE_ATTRIBUTES =
  4.             TypeAttributes.Public |
  5.             TypeAttributes.Interface |
  6.             TypeAttributes.Abstract |
  7.             TypeAttributes.AutoClass |
  8.             TypeAttributes.AnsiClass;
  9.  
  10.         private const BindingFlags GENERAL_FLAGS =
  11.             BindingFlags.Public |
  12.             BindingFlags.Instance;
  13.  
  14.         AssemblyBuilder _assemblyBuilder = null;
  15.         ModuleBuilder _moduleBuilder = null;
  16.         Type _mockeryType = null;
  17.         Type _bakedType = null;
  18.  
  19.         public Transformer(Type mockeryType)
  20.         {
  21.             _mockeryType=mockeryType;
  22.             AssemblyName assemblyName = new AssemblyName("DynamicModule");
  23.             _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
  24.             _moduleBuilder = _assemblyBuilder.DefineDynamicModule("DynamicMyClass.Module", "DynamicModule.dll", false);
  25.             _bakedType = CreateInterfaceType();
  26.             _assemblyBuilder.Save("DynamicModule.dll");
  27.         }
  28.  
  29.         private static Type[] GetParameterTypes(ParameterInfo[] paramInfos)
  30.         {
  31.             Type[] types = new Type[paramInfos.Length];
  32.             for (int i = 0; i < paramInfos.Length; ++i)
  33.             {
  34.                 types[i] = paramInfos[i].ParameterType;
  35.             }
  36.  
  37.             return types;
  38.         }
  39.  
  40.         private Type CreateInterfaceType()
  41.         {
  42.             TypeBuilder interfaceTypeBuilder =
  43.                 _moduleBuilder.DefineType("ID" + _mockeryType.Name, INTERFACE_TYPE_ATTRIBUTES, null);
  44.  
  45.             Converter<MethodInfo, MethodBuilder> defineInterfaceMethod = delegate(MethodInfo methodInfo)
  46.                                                                     {
  47.                                                                         return interfaceTypeBuilder.DefineMethod(
  48.                                                                             methodInfo.Name,
  49.                                                                             MethodAttributes.Public |
  50.                                                                             MethodAttributes.HideBySig |
  51.                                                                             MethodAttributes.SpecialName |
  52.                                                                             MethodAttributes.NewSlot |
  53.                                                                             MethodAttributes.Abstract |
  54.                                                                             MethodAttributes.Virtual,
  55.                                                                             CallingConventions.HasThis,
  56.                                                                             methodInfo.ReturnType,
  57.                                                                             GetParameterTypes(methodInfo.GetParameters())
  58.                                                                             );
  59.                                                                     };
  60.  
  61.             PropertyInfo[] classProps = _mockeryType.GetProperties(GENERAL_FLAGS);
  62.             foreach (PropertyInfo propertyInfo in classProps)
  63.             {
  64.                 PropertyBuilder propertyBuilder = interfaceTypeBuilder.DefineProperty(
  65.                     propertyInfo.Name,
  66.                     propertyInfo.Attributes,
  67.                     propertyInfo.PropertyType,
  68.                     null,
  69.                     null,
  70.                     GetParameterTypes(propertyInfo.GetIndexParameters()),
  71.                     null,
  72.                     null);
  73.                 if (propertyInfo.CanRead)
  74.                 {
  75.                     propertyBuilder.SetGetMethod(
  76.                         defineInterfaceMethod(propertyInfo.GetGetMethod(true))
  77.                         );
  78.                 }
  79.  
  80.                 if (propertyInfo.CanWrite)
  81.                 {
  82.                     propertyBuilder.SetSetMethod(
  83.                         defineInterfaceMethod(propertyInfo.GetSetMethod(true))
  84.                         );
  85.                 }
  86.             }
  87.  
  88.             return interfaceTypeBuilder.CreateType();
  89.         }
  90.  
  91.         private MethodBuilder DefineMethodInt(TypeBuilder interfaceTypeBuilder, MethodInfo methodInfo)
  92.         {
  93.              ParameterInfo[] pi = methodInfo.GetParameters();
  94.             Type[] tps = new Type[pi.Length];
  95.             for (int i = 0; i < tps.Length; i++)
  96.             {
  97.                 tps[i] = pi[i].ParameterType;
  98.             }
  99.             MethodBuilder methodBuilder = interfaceTypeBuilder.DefineMethod(methodInfo.Name,
  100.                 MethodAttributes.Public |
  101.                 MethodAttributes.HideBySig |
  102.                 MethodAttributes.SpecialName |
  103.                 MethodAttributes.NewSlot |
  104.                 MethodAttributes.Abstract |
  105.                 MethodAttributes.Virtual,
  106.             methodInfo.ReturnType, tps);
  107.             return methodBuilder;
  108.         }
  109.     }
  110.  
The goal is, having a class like:
Expand|Select|Wrap|Line Numbers
  1.     public class TransformTest
  2.     {
  3.         private string _SF;
  4.         public string SF
  5.         {
  6.             get { return _SF; }
  7.             set { _SF = value; }
  8.         }
  9.     };
  10.  
to get interface that looks like:
Expand|Select|Wrap|Line Numbers
  1.     public interface IDTransformTest
  2.     {
  3.         string SF{get;set;}
  4.     }
  5.  
Ok... Using the code above it seems like I built it... but (!!!) looking at IL representation of the newly generated type (using Reflector) here's what I see:

Expand|Select|Wrap|Line Numbers
  1. .class public interface abstract auto ansi IDTransformTest
  2. {
  3.     .property class string SF
  4.     {
  5.         .get instance string ConsoleApplication4.ITransformTest::get_SF()
  6.         .set instance void ConsoleApplication4.ITransformTest::set_SF(string)
  7.     }
  8. }
  9.  
while it should looks like this:
Expand|Select|Wrap|Line Numbers
  1. .class public interface abstract auto ansi ITransformTest
  2. {
  3.     .property instance string SF
  4.     {
  5.         .get instance string ConsoleApplication4.ITransformTest::get_SF()
  6.         .set instance void ConsoleApplication4.ITransformTest::set_SF(string)
  7.     }
  8. }
  9.  
The difference is in parameter standing right after .property qualifier:
class in my dynamic interface type
instance in the "real" interface type

What is wrong with my approach and how to correct it?

Thanks in advance for any help.
May 21 '07 #1
0 1277

Sign in to post your reply or Sign up for a free account.

Similar topics

3
23434
by: Hal Vaughan | last post by:
I'm creating a sequence of JPanels that will each, in turn, be added to (then removed from) a window (kind of like a wizard). I want these panels to not only extend the JPanel class, but to implement an interface. I have the interface defined in a separate class, like this: public interface IPanel { boolean onNext(); String nextPanel(); boolean hasCancel();
6
1246
by: Chamith | last post by:
Hi all, I have a method which takes a string parameter. It takes a type name as a string. Inside the method, i want to create an instance of the type which is mentioned in the string parameter. Please help me providing with some example code. Thanks,
2
2158
by: Pawan | last post by:
Hi Guys, I have this current assignment where I have to develop online forms for local municipal authorities. I have to use adobe acrobat to create online forms from PDFs (which I have never done before and have no idea how to do it). Now these online forms will be shared by 1200 users. VB and ASP will be used as glueware for the writing/coding. For eg, we will be creating navigation pages in ASP & linking into adobe. Any resource on this...
7
3678
by: yufufi | last post by:
lets say we have a 'shape' class which doesn't implement IComparable interface.. compiler doesn't give you error for the lines below.. shape b= new shape(); IComparable h; h=(IComparable)b; but it complains for the following lines
2
1313
by: Dan | last post by:
I have need to create a com server that will fire events back to clients. I have looked at some of the documentation and I am new to Python so cant quite get it. I have created an IDL file of the interfaces. Can someone tell me approximately what needs to be done here. I have seen examples of implementing the regular interfaces but don't know what to do about the events interfaces.The vid...Events interface is the main question here. In...
31
3205
by: JoeC | last post by:
I have read books and have ideas on how to create objects. I often create my own projects and programs. They end up getting pretty complex and long. I often use objects in my programs they are some of the most powerful programming tools I have found. Often times as my program grows so do my objects. Often times I look back and see that my objects could be broken down int several smaller more re-usable module pieces of code. Is it a...
3
2172
by: psbasha | last post by:
Hi, I would like to call the same aplication executable with and without Graphical User Interface. Requirement: With Tkinter User interface,user can give the inputs to run the application ( Interactive). Instead user will have this inputs in the file and it will be read by the batch utility or exe for the application For example:
6
2167
by: Chris Carlen | last post by:
Hi: I have an embedded system, platform: TI TMS320F2812 32-bit integer DSP. A module (.c file) contains external (to the funcs in that module) variables which are used to affect the operation of the program (other modules). These variables are only read by other parts of the program, but are to be set by a user interface which consists of an RS-232 terminal command line interface. The command parser for this interface responds to...
12
1380
by: ross m. greenberg | last post by:
I'm trying to create a function in JavaScript using Dreamweaver8 such that when a user hits the ' F1' key when a text box is selected a separate "pop-up" window will open, with text of my choice. Does anybody have any pointers or even some source code? I use ASP on my server. Thanks! Ross
7
9372
by: Jwe | last post by:
Hi, I've written a program which has both a command line interface and Windows form interface, however it isn't quite working correctly. When run from command line with no arguments it should display the Windows form. The form is being displayed but the command only returns when the form is closed. I want the command line to return immediately, leaving the form displayed.
0
9432
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10232
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
10059
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...
0
9873
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...
1
7420
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6682
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();...
0
5454
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3974
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
2
3578
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.