2010-07-06 37 views
4

我有2個非託管dll,它們具有完全相同的功能集(但略有不同的邏輯)。從另一個dll重裝dll函數,C#

如何在運行期間在這兩個ddls之間切換?

現在我有:

[DllImport("one.dll")] 
public static extern string _test_mdl(string s); 

回答

4

擴大現有的答案在這裏。您評論說您不想更改現有代碼。你不必這樣做。

[DllImport("one.dll", EntryPoint = "_test_mdl")] 
public static extern string _test_mdl1(string s); 

[DllImport("two.dll", EntryPoint = "_test_mdl")] 
public static extern string _test_mdl2(string s); 

public static string _test_mdl(string s) 
{ 
    if (condition) 
     return _test_mdl1(s); 
    else 
     return _test_mdl2(s); 
} 

你在你的現有代碼使用_test_mdl,並且只需將if語句在該方法的一個新版本,調用正確的基本方法。

+0

有點工作,但我需要環繞所有函數形式DLL :( – Halst 2010-07-06 23:31:18

4

定義他們在不同的C#類?

static class OneInterop 
{ 
[DllImport("one.dll")] 
public static extern string _test_mdl(string s); 
} 

static class TwoInterop 
{ 
[DllImport("two.dll")] 
public static extern string _test_mdl(string s); 
} 
+0

是的,你需要兩個類。 – sbenderli 2010-07-06 14:13:26

+2

如果您想將它們保留在同一個類中,您可以在'DllImport'屬性中設置'EntryPoint'屬性。 – 2010-07-06 14:15:21

+0

我想過,但他的問題是我在項目中使用了_test_mdl(),如果我在你的例子中使用_test_mdl(),那麼我需要更改代碼並使用if語句來調用_test_mdl – Halst 2010-07-06 14:16:18

4

我從來沒有使用過這個,但我認爲可以在聲明中指定EntryPoint。試試這個:

[DllImport("one.dll", EntryPoint = "_test_mdl")] 
    public static extern string _test_mdl1(string s); 

    [DllImport("two.dll", EntryPoint = "_test_mdl")] 
    public static extern string _test_mdl2(string s); 

DllImportAttribute.EntryPoint Field

1

你仍然可以使用動態加載並調用LoadLibraryEx(P/Invoke的),GetProcAddress(P/Invoke的)和Marshal.GetDelegateForFunctionPointer(System.Runtime.InterOpServices)。

;)