gpt4 book ai didi

.net - 如何检测dll是否是COM dll

转载 作者:行者123 更新时间:2023-12-02 00:34:45 25 4
gpt4 key购买 nike

我想确定 dll 是否需要注册为部署工具的一部分。所以它可能是任何类型的 com dll、.net 或其他类型。它可能已注册,也可能未注册。所以这个问题与 How to determine if DLL is COM or .NET? 有点不同.

我的函数签名是:

public bool? IsComDll(string Path)
{

}

我想直接检查dll,而不是注册它来查找,因为这会留下副作用。

我不介意使用Assembly如果它碰巧是 .Net dll,则可以运行,但我不会提前知道,而且我还需要处理非 .Net dll。

编辑:

这是我到目前为止的代码。它可以工作,但在可能是也可能不是 COM 的非 .net dll 上除外,其中 LoadLibrary返回零指针,这可能是由于其他原因(例如依赖性问题)造成的。某些 COM dll 工作正常并返回 true,例如 C:\Windows\System32\vbscript.dll 。所以我猜你可以说它至少在 75% 的时间内有效。

public T GetAttribute<T>(string AssemblyPath)
{
return GetAttribute<T>(Assembly.LoadFile(AssemblyPath));
}

public T GetAttribute<T>(Assembly Assembly)
{
return Assembly.GetCustomAttributes(typeof(T), false).FirstOrDefault;
}

public bool? IsComDll(string Path)
{

if (IsDotNetDll(Path)) {
ComVisibleAttribute ComVisibleAttribute = GetAttribute<ComVisibleAttribute>(Path);
return ComVisibleAttribute != null && ComVisibleAttribute.Value;
}

if (Path.Contains(" ")) {
Path = string.Format("\"{0}\"", Path);
}

IntPtr hModuleDLL = LoadLibrary(Path);

if (hModuleDLL == IntPtr.Zero) {
//we can't tell
//TODO: Find out how!
}

// Obtain the required exported API.
IntPtr pExportedFunction = IntPtr.Zero;

pExportedFunction = GetProcAddress(hModuleDLL, "DllRegisterServer");

return pExportedFunction != IntPtr.Zero;

}

public bool IsDotNetDll(string Path)
{
try {
Assembly.LoadFile(Path);
return true;
} catch (BadImageFormatException bifx) {
return false;
} catch (Exception ex) {
throw;
}
}

最佳答案

有一些工具可以在开发时提供帮助。这些方法是手动的,但通常安装程序仅构建一次,因此这种方法可以获得所需的信息。

  1. 我经常在我的系统上运行 OLEView (C:\Program Files (x86)\Microsoft Visual Studio\Common\Tools\OLEVIEW.EXE - 可能VB6/Visual Studio 6 附带)并尝试打开有问题的 DLL。如果它是一个 COM DLL,OLEView 将很好地显示其 IDL 等的转储。否则会出现一些错误。

    这有点“快速而肮脏”,但对我来说效果很好。

    (2020 更新)OLEView 有一个替代项目,名为 OLEViewDotNet它拥有改进的功能。讨论过here .

  2. Dependency Walker (C:\Program Files (x86)\Microsoft Visual Studio\Common\Tools\DEPENDS.EXE) 可用于检查 DLL 以查看它是否包含特征 COM 函数导出。例如,以下是加载 mscomct2.ocx 的示例:

enter image description here

正如另一个答案中所述,函数 DLLRegisterServerDLLUnregisterServer 是 COM DLL 的典型/必需函数,因此它们的存在几乎肯定意味着它就是这样。

关于.net - 如何检测dll是否是COM dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28305017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com