2012-09-10 36 views
0

可能重複:
How to separate managed and unmanaged DLLs in another directory編程方式更改非託管DLL的位置導入

我使用非託管代碼與我的C#託管代碼。我在應用程序的可執行文件中嵌入了非託管DLL。爲了做到這一點,我在對DLL方法進行調用之前,先將資源/ DLL提取到文件中。

public static class ResourceExtractor 
{ 
    public static void ExtractResourceToFile(string resourceName, string filename) 
    { 
     if (!System.IO.File.Exists(filename)) 
      using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) 
      using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create)) 
      { 
       byte[] b = new byte[s.Length]; 
       s.Read(b, 0, b.Length); 
       fs.Write(b, 0, b.Length); 
      } 
    } 
} 

所以,在我做的DLL調用我一定要做到以下幾點:

ResourceExtractor.ExtractResourceToFile("Namespace.dll_name.dll", "dll_name.dll"); 

而且包住非託管的DLL我的方法...

public class DLLWrapper 
{ 
    public const string dllPath = "dll_name.dll"; 

    [DllImport(dllPath)] 
    public static extern uint functionA(); 

    [DllImport(dllPath)] 
    public static extern uint functionB(); 

    [DllImport(dllPath)] 
    public static extern uint functionC(); 
} 

現在的問題...

這一切工作。什麼我不要就像它創建的DLL坐在可執行文件旁邊。我寧願在一個臨時目錄中創建DLL並從那裏加載它。喜歡的東西...

string tempDLLname = Path.GetTempFileName(); 
ResourceExtractor.ExtractResourceToFile("Namespace.dll_name.dll", tempDLLname); 
DLLWrapper.dllPath = tempDLLname; 

... 

public class DLLWrapper 
{ 
    public static string dllPath; 

    [DllImport(dllPath)] 
    public static extern uint functionA(); 

    [DllImport(dllPath)] 
    public static extern uint functionB(); 

    [DllImport(dllPath)] 
    public static extern uint functionC(); 
} 

然而,這並不工作,因爲[DllImport(path)]需要的路徑是一個const。那麼你如何改變你想要加載DLL的位置呢?直到運行時我纔會知道。

回答

4

在調用針對dll的任何調用之前,您可以明確地使用LoadLibrary並傳入您將其解壓到的完整路徑。

http://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx

+0

請問您可以擴展此答案嗎?我檢查了你的鏈接,但我不清楚如何實際實現這一點。 –

+0

立即將dll提取到臨時位置後,使用該完整路徑調用LoadLibrary將其加載到進程內存中。只要dll * name *與您在DllImport中使用的內容相匹配,對導出函數的後續調用將由加載的dll處理。對於同一個進程,相同的dll名稱不能在內存中加載兩次。 – tcarvin

+0

工程就像一個魅力。非常感謝你。 –

相關問題