繁体   English   中英

C#DllImport不存在的功能

[英]C# DllImport of non-existent function

我们有一些C#代码,可从外部DLL调用非托管代码。 外部DLL用作插件,并且可以具有不同的版本。 不同版本包含的可用功能略有不同。

当我们DllImport一个不存在的函数时会发生什么? 当我们称呼它会怎样? 我们可以在调用Dll之前知道Dll中是否有特定功能吗?

更具体地说,DLL的最新版本具有为我们提供该版本的功能。 因此,对于这些版本,很容易知道哪些功能可用。 但是,我们还需要知道DLL是否具有比引入此功能的地方更旧的版本。

.net运行时将按需JIT您的代码。 这就是您完成此操作的方式。

如果您依赖依赖于可能存在或可能不存在DLL函数的代码的惰性实例化。 您可以使用GetProcAddress函数检查该函数。 如果我们正在编写旧的Win32代码,这就是我们要做的。

这是乔恩·斯基特(Jon Skeet)关于懒惰的文章中的一个简单示例:

public sealed class Singleton
{
  [DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
  private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

  [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
  private static extern IntPtr GetModuleHandle(string lpModuleName);

  public bool IsQueryFullProcessImageNameSupported { get; private set; }

  public string QueryFullProcessImageName(IntrPtr handle)
  { 
    if (!IsQueryFullProcessImageNameSupported) {
      throw new Exception("Does not compute!");
    }
    int capacity = 1024;
    var sb = new StringBuilder(capacity);
    Nested.QueryFullProcessImageName(handle, 0, sb, ref capacity);
    return sb.ToString(0, capacity);
  }

  private Singleton()
  {
    // You can use the trick suggested by @leppie to check for the method
    // or do it like this. However you need to ensure that the module 
    // is loaded for GetModuleHandle to work, otherwise see LoadLibrary
    IntPtr m = GetModuleHandle("kernel32.dll");
    if (GetProcAddress(m, "QueryFullProcessImageNameW") != IntrPtr.Zero) 
    {
      IsQueryFullProcessImageNameSupported = true;
    }
  }

  public static Singleton Instance { get { return Nested.instance; } }

  private class Nested
  {
    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Nested()
    {
      // Code here will only ever run if you access the type.
    }

    [DllImport("kernel32.dll", SetLastError=true)]
    public static extern bool QueryFullProcessImageName([In]IntPtr hProcess, [In]int dwFlags, [Out]StringBuilder lpExeName, ref int lpdwSize);

    public static readonly Singleton instance = new Singleton();
  }
}

懒惰是在JITting中继承的,这并不是必须的。 但是,它确实允许我们保持一致的命名约定。

在调用方法之前,使用Marshal.Prelink(MethodInfo)检查它是否有效。

如果您尝试调用不存在的函数,则会抛出EntryPointNotFoundException

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM