Dynamic Compilation and Loading of .NET Objects
Introduction
When I read about dynamic compilation in .NET (which is a great feature) for the first time, I soon got stuck with the samples I found. Mostly, they covered the idea of writing small functions dynamically as we can find on various web pages with tutorials. These samples discuss problems like speed of execution or different ways to access the compiled function. But I wanted more. My idea was: I want to compile and use an whole object (or even some more) with members and methods without taking too much care about reflection (yes, some reflection is necessary, I know).
Using the Code
Basically, our best friends here are Microsoft.CSharp and System.CodeDom.Compiler. But to make this simple magic of having an instance of the dynamically compiled object, we also use a simple interface like this:
using System;
namespace Iface {
public interface ImyInterface
{
string text {get; set;}
int number {get; set;}
int Func (int a, int b);
}
}
To make this interface available to the dynamically compiled code, I put this interface into a calls library, called "Iface.dll".
For the basic program, I add a reference to the Iface.dll and add the namespace together with all others necessary for this example:
using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
using Iface;
The code for the dynamically compiled object is as follows:
const string code=@"
using System;
namespace TestClass
{
public class MyClass : Iface.ImyInterface
{
public int i;
public string text {get; set;}
public int number {get; set;}
public int Func (int a, int b){
i=a+b;
return a+b;
}
}
}
";
As you can see, it's just an implementation of the interface doing nothing special.
For the compilation at runtime, we need a CSharpCodeProvider and CompilerParameters:
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("Iface.dll");
parameters.GenerateInMemory = true;
Please note: When the program is compiled, a copy of the "Iface.dll" is placed in the same directory as the executable. So, the path for the referenced assembly is limited to "Iface.dll".
Next step: Compilation and some error handling.
CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.HasErrors)
{
StringBuilder sb = new StringBuilder();
foreach (CompilerError error in results.Errors)
{
sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
}
throw new InvalidOperationException(sb.ToString());
}
And finally we get our object:
Assembly assembly = results.CompiledAssembly;
Type asmType = assembly.GetType("TestClass.MyClass");
Type[] argTypes=new Type[] { };
ConstructorInfo cInfo=asmType.GetConstructor(argTypes);
ImyInterface myclass=(ImyInterface)cInfo.Invoke(null); int result=myclass.Func(1,2);
Console.WriteLine("and the result is: {0}",result);
Console.ReadKey(true);
Dynamic Compilation and Loading of .NET Objects的更多相关文章
- Delphi DLL制作和加载 Static, Dynamic, Delayed 以及 Shared-Memory Manager
一 Dll的制作一般分为以下几步:1 在一个DLL工程里写一个过程或函数2 写一个Exports关键字,在其下写过程的名称.不用写参数和调用后缀.二 参数传递1 参数类型最好与window C++的参 ...
- ora-00600笔记
一. ORA-600 概述 Errorsof the form ORA-600 are called internal errors. This section clarifies themisund ...
- Unity 5 Game Optimization (Chris Dickinson 著)
1. Detecting Performance Issues 2. Scripting Strategies 3. The Benefits of Batching 4. Kickstart You ...
- IronPython Architecture
[IronPython] IronPython is an implementation of the Python programming language written by the CLR t ...
- oracle-Expdp/impdp命令
建立逻辑路径 create or replace directory dumpdir as 'c:\'; grant read,write on directory dumpdir to scott; ...
- Orchard源码分析(5.1):Host初始化(DefaultOrchardHost.Initialize方法)
概述 Orchard作为一个可扩展的CMS系统,是由一系列的模块(Modules)或主题(Themes)组成,这些模块或主题统称为扩展(Extensions).在初始化或运行时需要对扩展进行安装:De ...
- [你必须知道的.NET]第三十一回,深入.NET 4.0之,从“新”展望
发布日期:2009.05.22 作者:Anytao © 2009 Anytao.com ,Anytao原创作品,转贴请注明作者和出处. /// <summary> /// 本文开始,将以& ...
- SCI&EI 英文PAPER投稿经验【转】
英文投稿的一点经验[转载] From: http://chl033.woku.com/article/2893317.html 1. 首先一定要注意杂志的发表范围, 超出范围的千万别投,要不就是浪费时 ...
- 【转载】Android Studio 设置内存大小及原理
http://www.cnblogs.com/justinzhang/p/4274985.html http://tsroad.lofter.com/post/376316_69363ae Andro ...
随机推荐
- Mysql 里CHAR和VARCHAR的最大长度及一些注意事项
先写出结论: Mysql 5中 非空CHAR的最大总长度是255[字节]:非空VARCHAR的最大总长度是65533[字节]. 可空CHAR的最大总长度是254[字节]:可空VARCHAR的最大总长度 ...
- Js基础知识(一) - 变量
js基础 - 变量 *大家对js一定不会陌生,入门很简单(普通入门),很多人通过网络资源.书籍.课堂等很多途径学习js,但是有些js基础的只是往往被大家遗漏,本章就从js变量类型来说一说js 变量类型 ...
- springboot 使用redis
安装redis教程:https://www.cnblogs.com/nongzihong/p/10190489.html 依赖: <!--配置redis--> <dependency ...
- C++入门经典-例5.13-内存安全,被销毁的内存
1:当指针所指向的内存被销毁时,该区域不可复用.若有指针指向该区域,则需要将该指针置为空值(NULL)或者指向未被销毁的内存. 内存销毁实质上是系统判定该内存不是变成人员正常使用的空间,系统也回将它们 ...
- JS 由前端保存到文件
function doSave(value, type, name) { var blob; if (typeof window.Blob == "function") { blo ...
- C语言中的!!
C语言中!!的作用是?看例子: #include <stdio.h> int main() { ; printf("test=%d !test=%d !!test=%d\n&qu ...
- note:memcache 調試遇到的一些問題
1. gdb調試時提示:<value optimized out> ,原因是memcache的編譯选项做了优化,修改configure中CFLAGS中的-O3为-O0,可以解决gdb调试过 ...
- P1200 [USACO1.1]你的飞碟在这儿Your Ride Is He…
P1200 [USACO1.1]你的飞碟在这儿Your Ride Is He… 大写祖母转数字 -64 发现dalao #include<bits/stdc++.h> usi ...
- OpenCV学习笔记(7)——图像阈值
简单阈值,自适应阈值,Otsu's二值化等 1.简单阈值 当像素值高于阈值时,我们给这个像素赋予一个新值,否则给他赋予另一个值.这个函数就是cv2.threshhold().这个函数的第一个参数就是原 ...
- leetcode -1 count the path