【问题标题】:Load dynamic library and use functions inside the library加载动态库并使用库内的函数
【发布时间】:2020-02-17 08:28:43
【问题描述】:

在 C# 中,我使用外部 dll,使用 loadLibrary,如下所示:

public class Utilities
    [DllImport("kernel32", CharSet= CharSet.Auto, SetLastError=true)]
    private static extern IntPtr LoadLibrary(string librayName);
    [DllImport("kernel32", CharSet= CharSet.Auto, SetLastError=true)]
    private static extern IntPtr GetProcAddress(intPtr hwnd, string procedureName);

    public static LoadAssembliesAndMethods() {
        string mainPath = AppDomain.CurrentDomain.BaseDirectory;
        string path = Path.Combine(mainPath, "MyAssembly.dll");

        IntPtr ptr = LoadLibrary(path);

        // What to do next in order to get all the list of functions/methods/class in the library and use them?

    }

这个dll没有Assembly的签名(它是第3方),所以我做不到

Assebly.LoadFile(path);

我需要获取 dll 的所有函数/方法/类,并使用其中的一些,使用 C#。

我该怎么做。

【问题讨论】:

  • 你要加载什么样的dll库?
  • LoadLibrary then GetProcAddress(hLibrary, functionName) 返回所需函数的地址 (IntPtr)
  • 我不知道希望函数是在静态类中还是只是一个函数。我没有第 3 方库的来源。我需要检查类列表和方法列表,然后使用它们。

标签: c# dynamic-library


【解决方案1】:

如果您想列出非托管 dll 中的所有方法,此链接可以帮助您:

C# get the list of unmanaged C dll exports

更新:

IntPtr funcaddr = GetProcAddress(Handle,functionName);
YourFunctionDelegate function = 
Marshal.GetDelegateForFunctionPointer(funcaddr,typeof(YourFunctionDelegate )) 
as YourFunctionDelegate ;
function.Invoke(pass here your parameters);

您需要在编码时创建委托或使用 DynamicModules 在运行时创建委托

【讨论】:

  • 谢谢。那是帮助。我看到函数“AFunc” - 我如何调用该函数?谢谢。
  • @Eitan 检查更新,使用 Delegate.CreateDelegate 在运行时创建委托
  • 执行后: IntPtr ptr = LoadLibrary(path) (作为我的代码); & IntPtr funcaddr = GetProcAddress(Handle,functionName);我得到 funcaddr=0x00000000,而不是有效地址(即使我看到函数名称在列表中(如您提供的链接:stackoverflow.com/questions/18249566/…
  • 好的。发现错误:正如我在stackoverflow.com/questions/3754264/… 上看到的,我看到我需要更改GetProcAddress 的装饰器:CharSet = CharSet.Ansi
  • 另外,你能给我一个例子吗:GetDelegateForFunctionPointer(IntPtr)
【解决方案2】:

没有通用的方法来以编程方式获取非托管库的导出列表。

更多信息请见Is there a way to find all the functions exposed by a dll

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 2012-08-03
    • 2021-10-18
    • 2020-07-22
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多