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 ...
随机推荐
- Java程序,JVM之间的关系
java程序是跑在JVM上的,严格来讲,是跑在JVM实例上的.一个JVM实例其实就是JVM跑起来的进程,二者合起来称之为一个JAVA进程.各个JVM实例之间是相互隔离的. 每个java程序都运行于某个 ...
- 第三天·HTML常用标签
一·<h1>-<h6> 单词缩写:headHTML的<h1>-<h6>代表了六个等级的标题,其中<h1>标签比较重要,因此要尽量少用.一般& ...
- 阶段3 2.Spring_06.Spring的新注解_7 spring整合junit问题分析
测试类重复代码的问题 这是之前的方式 运行findAll的方法,没有问题 测试人员不需要关心上面的方法,.应该关心的各个方法是否能够正常的运行 对于一个测试工程师,只要写完变量就可以测试了. 可以使用 ...
- 四十二:数据库之SQLAlchemy之数据查询懒加载技术
懒加载在一对多,或者多对多的时候,如果要获取多的这一部分的数据的时候,通过一个relationship定义好对应关系就可以全部获取,此时获取到的数据是list,但是有时候不想获取全部数据,如果要进行数 ...
- 对redis的一些理解
缓存就是在内存中存储的数据备份,当数据没有发生本质变化的时候,我们避免数据的查询操作直接连接数据库,而是去 内容中读取数据,这样就大大降低了数据库的读写次数,而且从内存中读数据的速度要比从数据库 ...
- GitHub Port 443 Refused
最近在本地Github上传和更新远程仓库的时候老是显示 GitHub - failed to connect to github 443 windows/ Failed to connect to g ...
- 2019.03.30 Dialog demo 一个标准使用的dialog程序
PROGRAM zdemo_dialog. INCLUDE zdemo_dialogtop. INCLUDE zdemo_dialogo01. INCLUDE zdemo_dialogi01. INC ...
- caffe-----使用C++ 提取网络中间层特征数据
最近实验,想要在c++下知道网络中间某一层的特征数据情况,查找了相关资料,记录一下. 其实在caffe框架里面是包含这种操作的,可以模仿tools/extract_features.cpp中的操作来得 ...
- windows vs2015 编译openssl 1.1.0c
1,到openssl官网下载源码. 2,安装activePerl,我放在网盘:https://pan.baidu.com/s/1ZHe24yRcPtIuSiEa-3oqxw 3.安装完毕后,使用 VS ...
- gin框架教程一: go框架gin的基本使用
我们在用http的时候一般都会用一些web框架来进行开发,gin就是这样的一个框架,它有哪些特点呢 一:gin特点 1.性能优秀2.基于官方的net/http的有限封装3.方便 灵活的中间件4.数据绑 ...