从另一个dll重新加载dll函数,C#

4

我有两个未托管的dll文件,它们拥有完全相同的函数集(但略有不同的逻辑)。

在运行时如何在这两个dll之间切换?

现在我的代码是:

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

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);
}

是的,您需要两个类。 - sbenderli
2
如果您想将它们保留在同一类中,可以在 DllImport 属性中设置 EntryPoint 属性。 - Stephen Cleary
我考虑过这个问题,但是问题在于我在项目中经常使用_test_mdl()。如果按照你的例子去做,我需要改变代码并且为每次调用_test_mdl加上if语句。 - Vladimir Keleshev

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


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语句,调用正确的基础方法即可。

那应该可以工作,但我需要包装所有来自dll的函数 :( - Vladimir Keleshev

1
你仍然可以使用动态加载并调用 LoadLibraryEx (P/Invoke)、GetProcAddress (P/Invoke) 和 Marshal.GetDelegateForFunctionPointer (System.Runtime.InterOpServices)。
; )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接