我正在尝试找到一种在 P/Invoking 之前检测功能是否存在的好方法。例如调用原生StrCmpLogicalW
函数:
[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
public static extern int StrCmpLogicalW(string psz1, string psz2);
}
在某些没有此功能的系统上会崩溃。
我不想执行版本检查,因为这是不好的做法,有时可能是错误的(例如,当功能被向后移植时,或者当功能可以被卸载时)。
正确的方法是检查是否存在来自的导出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);
}
当然,问题在于 C# 不支持函数指针,即:
_StrCmpLogicalW = GetProcedure("shlwapi.dll", "StrCmpLogicalW");
无法完成。
所以我试图找到替代语法来在.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);
}
}
我需要一些帮助。
我想检测存在的一些出口的另一个例子是:
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 中执行特征检测的首选方式的示例?