P /调用C#和.NET时的功能检测

Ian*_*oyd 13 c# pinvoke feature-detection

我正试图在P/Invoking之前找到一种检测特征是否存在的好方法.例如,调用本机StrCmpLogicalW函数:

[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
   [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
   public static extern int StrCmpLogicalW(string psz1, string psz2);
}
Run Code Online (Sandbox Code Playgroud)

将在某些没有此功能的系统上崩溃.

我不想执行版本检查,因为这是不好的做法,有时可能只是错误(例如,当功能被反向移植时,或者可以卸载功能时).

正确的方法是检查导出的存在shlwapi.dll:

private static _StrCmpLogicalW: function(String psz1, String psz2): Integer;
private Boolean _StrCmpLogicalWInitialized;

public int StrCmpLogicalW(String psz1, psz2)
{
    if (!_StrCmpLogialInitialized)
    {
        _StrCmpLogicalW = GetProcedure("shlwapi.dll", "StrCmpLogicalW");
        _StrCmpLogicalWInitialized = true;
    }

    if (_StrCmpLogicalW)
       return _StrCmpLogicalW(psz1, psz2)
    else
       return String.Compare(psz1, psz2, StringComparison.CurrentCultureIgnoreCase);
}
Run Code Online (Sandbox Code Playgroud)

当然,问题是C#不支持函数指针,即:

_StrCmpLogicalW = GetProcedure("shlwapi.dll", "StrCmpLogicalW");
Run Code Online (Sandbox Code Playgroud)

无法做到.

所以我试图找到替代语法来在.NET中执行相同的逻辑.到目前为止我有以下伪代码,但我受到了阻碍:

[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
   private Boolean IsSupported = false;
   private Boolean IsInitialized = false;

   [DllImport("shlwapi.dll", CharSet = CharSet.Unicode, Export="StrCmpLogicalW", CaseSensitivie=false, SetsLastError=true, IsNative=false, SupportsPeanutMandMs=true)]
   private static extern int UnsafeStrCmpLogicalW(string psz1, string psz2);

   public int StrCmpLogicalW(string s1, string s2)
   {
       if (!IsInitialized) 
       {
          //todo: figure out how to loadLibrary in .net
          //todo: figure out how to getProcedureAddress in .net
          IsSupported = (result from getProcedureAddress is not null);
          IsInitialized = true;
       }

       if (IsSupported) 
          return UnsafeStrCmpLogicalW(s1, s2);
       else
          return String.Compare(s1, s2, StringComparison.CurrentCultureIgnoreCase);
   }
}
Run Code Online (Sandbox Code Playgroud)

我需要一些帮助.


我想要检测存在的一些导出的另一个例子是:

  • dwmapi.dll::DwmIsCompositionEnabled
  • dwmapi.dll::DwmExtendFrameIntoClientArea
  • dwmapi.dll::DwmGetColorizationColor
  • dwmapi.dll::DwmGetColorizationParameters(未记录1,尚未按名称导出,序号127)
  • dwmapi.dll::127(未记录的1,DwmGetColorizationParameters)

1从Windows 7 SP1开始

.NET中必须已有一个设计模式用于检查操作系统功能的存在.有人能指出我在.NET中执行特征检测的首选方法的示例吗?

Joh*_*ell 6

你可以P/Invoke来LoadLibraryW加载shlwapi.dll,然后P/Invoke GetProcAddressW来找到"StrCmpLogicalW".如果返回NULL,则它不存在.

您不需要实际的返回值GetProcAddressW- 只要它不是NULL,您就知道可以使用您选择的P/Invoke声明.

请注意,GetProcAddressW它还支持按序数值导出的函数.

编辑:如果你想要遵循某种模式,那么这可能会起作用:

首先定义一个帮助器类NativeMethodResolver,告诉您库中是否存在方法:

public static class NativeMethodResolver
{
    public static bool MethodExists(string libraryName, string methodName)
    {
        var libraryPtr = LoadLibrary(libraryName);
        var procPtr = GetProcAddress(libraryPtr, methodName);

        return libraryPtr != UIntPtr.Zero && procPtr != UIntPtr.Zero;
    }

    [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern UIntPtr LoadLibrary(string lpFileName);

    [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
    private static extern UIntPtr GetProcAddress(UIntPtr hModule, string lpProcName);
}
Run Code Online (Sandbox Code Playgroud)

上面的辅助类可以被SafeNativeMethod那些辅助锅炉电镀的派生类消耗掉一些常见的东西:

public abstract class SafeNativeMethod
{
    private readonly string libraryName;
    private readonly string methodName;
    private bool resolved;
    private bool exists;

    protected SafeNativeMethod(string libraryName, string methodName)
    {
        this.libraryName = libraryName;
        this.methodName = methodName;
    }

    protected bool CanInvoke
    {
        get
        {
            if (!this.resolved)
            {
                this.exists = Resolve();
                this.resolved = true;
            }

            return this.exists; 
        }            
    }

    private bool Resolve()
    {
        return NativeMethodResolver.MethodExists(this.libraryName, this.methodName);
    }
}
Run Code Online (Sandbox Code Playgroud)

定义自己的Invoke方法的派生类然后可以调用基类CanInvoke以查看是否应该返回默认值(或默认实现)来代替所寻找的本机方法的返回值.根据您的问题,我将把shlwapi.dll/StrCmpLogicalWdwmapi.dll/DwmIsCompositionEnabled作为示例实现SafeNativeMethod:

public sealed class SafeStrCmpLogical : SafeNativeMethod
{
    public SafeStrCmpLogical()
        : base("shlwapi.dll", "StrCmpLogicalW")
    {           
    }

    public int Invoke(string psz1, string psz2)
    {
        return CanInvoke ? StrCmpLogicalW(psz1, psz2) : 0;
    }

    [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern int StrCmpLogicalW(string psz1, string psz2);
}

public sealed class SafeDwmIsCompositionEnabled : SafeNativeMethod
{
    public SafeDwmIsCompositionEnabled()
        : base("dwmapi.dll", "DwmIsCompositionEnabled")
    {
    }

    public bool Invoke()
    {
        return CanInvoke ? DwmIsCompositionEnabled() : false;
    }

    [DllImport("dwmapi.dll", SetLastError = true, PreserveSig = false)]
    private static extern bool DwmIsCompositionEnabled();
}
Run Code Online (Sandbox Code Playgroud)

然后可以像这样使用这两个:

static void Main()
{
    var StrCmpLogical = new SafeStrCmpLogical();
    var relation = StrCmpLogical.Invoke("first", "second");

    var DwmIsCompositionEnabled = new SafeDwmIsCompositionEnabled();
    var enabled = DwmIsCompositionEnabled.Invoke();
}
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用Marshal.GetDelegateForFunctionPointer()将返回的地址转换为委托. (3认同)