C# 實現動態載入DLL外掛程式 及HRESULT:0x80131047處理

來源:互聯網
上載者:User

標籤:winform   style   blog   io   color   ar   os   使用   for   

本代碼實現DLL的動態載入, 類似PS裡的濾鏡外掛程式!

1. 建立一個介面項目類庫,此處名稱為:Test.IPlugin

using System;namespace Test.IPlugin{    public interface IPlugin    {        void Run(object obj);    }}

2.建立一個DLL外掛程式類庫項目,此項目要引用介面項目‘Test.IPlugin‘,並實現Run方法, 此處名稱為:Test.Plugin

using System;namespace Test.Plugin{    public class Plugin:IPlugin.IPlugin    {        #region IPlugin 成員        void Test.IPlugin.IPlugin.Run(object obj)        {            System.Windows.Forms.MessageBox.Show(obj.ToString());        }        #endregion    }}

3.外掛程式動態載入實現,建立控制台或者WinForm項目及引用介面項目Test.IPlugin, 以下為動態載入代碼

private void btnLoad_Click(object sender, EventArgs e){    string filePath = @"檔案路徑\Test.Plugin.dll";    Assembly dll = null;    {//方法一:直接從DLL路徑載入(網上代碼,本機測試出錯)        //dll = Assembly.Load(filePath);     }    {//方法二:先把DLL載入到記憶體,再從記憶體中載入        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);        BinaryReader br = new BinaryReader(fs);        byte[] bFile = br.ReadBytes((int)fs.Length);        br.Close();        fs.Close();        dll = Assembly.Load(bFile);    }    //調用介面    foreach (var t in dll.GetTypes())    {        if (t.GetInterface("IPlugin") != null)        {            var plugin = (IPlugin.IPlugin)Activator.CreateInstance(t);            plugin.Run("test");        }    }}

以上為實現動態外掛程式模式的代碼,先注意下調用外掛程式的代碼中有2種方法

----------------分割線---------------

注意第一種方法, 在Assembly.Load(filePath)時會拋出異常: 

  未能負載檔案或程式集“***”或它的某一個依賴項。給定程式集名稱或基本代碼無效。 (異常來自 HRESULT:0x80131047)

在網上查了很多相關解決方案均未能解決這個錯誤,開發環境為VS2008,三個項目均為Framework2.0 X86模式,嘗試過的方式

  1.強制CPU模式為X86  2.所有DLL及EXE放置同一目錄  3.取消"啟用Visual Studio宿主進程"

 

最後無意中看到有用載入到記憶體的方式,然後使用BinaryReader讀取位元組數組再載入, 完美解決.

 

C# 實現動態載入DLL外掛程式 及HRESULT:0x80131047處理

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.