熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

詳解.NET中的動態編譯技術[4]

2022-06-13   來源: .NET編程 

  接下來在原來基礎上需要修改的是

  · 將編譯成的DLL保存到磁盤中

  · 創建另外的AppDomain

  · 獲得IRemoteInterface接口的引用(將生成的DLL加載到額外的AppDomain)

  · 調用InvokeMethod方法來遠程調用

  · 可以通過AppDomainUnload()方法卸載程序集

  以下是完整的代碼演示了如何應用這一方案

//get the code to compile

string strSourceCode = thistxtSourceText;

 

// Create an addtional AppDomain

AppDomainSetup objSetup = new AppDomainSetup();

objSetupApplicationBase = AppDomainCurrentDomainBaseDirectory;

AppDomain objAppDomain = AppDomainCreateDomain(MyAppDomain null objSetup);

 

// Create a new CSharpCodePrivoder instance

CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();

 

// Sets the runtime compiling parameters by crating a new CompilerParameters instance

CompilerParameters objCompilerParameters = new CompilerParameters();

objCompilerParametersReferencedAssembliesAdd(Systemdll);

objCompilerParametersReferencedAssembliesAdd(SystemWindowsFormsdll);

 

// Load the remote loader interface

objCompilerParametersReferencedAssembliesAdd(RemoteAccessdll);

 

// Load the resulting assembly into memory

objCompilerParametersGenerateInMemory = false;

objCompilerParametersOutputAssembly = DynamicalCodedll;

 

// CompilerResults: Complile the code snippet by calling a method from the provider

CompilerResults cr = objCSharpCodePrivoderCompileAssemblyFromSource(objCompilerParameters strSourceCode);

if (crErrorsHasErrors)

{

    string strErrorMsg = crErrorsCountToString() + Errors:;

    for (int x = ; x < crErrorsCount; x++)

    {

        strErrorMsg = strErrorMsg + \r\nLine: +

                     crErrors[x]LineToString() + +

                     crErrors[x]ErrorText;

    }

    thistxtResultText = strErrorMsg;

    MessageBoxShow(There were build erros    please modify your code Compiling Error);

 

    return;

}

// Invoke the method by using Reflection

RemoteLoaderFactory factory = (RemoteLoaderFactory)objAppDomainCreateInstance(RemoteAccessRemoteAccessRemoteLoaderFactory)Unwrap();

// with help of factory create a real LiveClass instance

object objObject = factoryCreate(DynamicalCodedll DynamiclyHelloWorld null);

 

if (objObject == null)

{

    thistxtResultText = Error: + Couldnt load class;

    return;

}

// *** Cast object to remote interface avoid loading type info

IRemoteInterface objRemote = (IRemoteInterface)objObject;

object[] objCodeParms = new object[];

objCodeParms[] = Allan;

string strResult = (string)objRemoteInvoke(GetTime objCodeParms);

thistxtResultText = strResult;

//Dispose the objects and unload the generated DLLs

objRemote = null;

AppDomainUnload(objAppDomain);

SystemIOFileDelete(DynamicalCodedll);

[]  []  []  []  []  


From:http://tw.wingwit.com/Article/program/net/201311/14505.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.