IntPtr.ToInt32() Marshal.ThrowExceptionForHR() - 查询 GAC

Mar*_*lon 2 .net c# interop gac fusion

我一直在使用我在网上找到的一些代码来使用 fusion.dll 查询 GAC,但是我最近收到了一些错误报告,抱怨溢出异常。

    // If assemblyName is not fully qualified, a random matching may be returned!!!!
    public static String QueryAssemblyInfo(String assemblyName)
    {
        ASSEMBLY_INFO assembyInfo = new ASSEMBLY_INFO();
        assembyInfo.cchBuf = 512;
        assembyInfo.currentAssemblyPath = new String('\0',
        assembyInfo.cchBuf);
        IAssemblyCache assemblyCache = null;
        // Get IAssemblyCache pointer
        IntPtr hr = GacApi.CreateAssemblyCache(out assemblyCache, 0);
        if (hr == IntPtr.Zero)
        {
            hr = assemblyCache.QueryAssemblyInfo(1, assemblyName, ref assembyInfo);
            if (hr != IntPtr.Zero)
                Marshal.ThrowExceptionForHR(hr.ToInt32());
        }
        else
            Marshal.ThrowExceptionForHR(hr.ToInt32());
        return assembyInfo.currentAssemblyPath;
    }
Run Code Online (Sandbox Code Playgroud)

有问题的代码是当它实际上是 Int64 时试图将 IntPtr 转换为 Int32,但问题是 Marshal.ThrowExceptionForHR 只接受 Int32,所以我有点不知道该怎么做。目前我只是在处理异常,但我想知道正确的做法是什么?

马龙

Phi*_*unt 5

检查您的DllImportfor上的签名CreateAssemblyCache。看起来应该是int,不是IntPtr

[DllImport("fusion.dll")]
internal static extern int CreateAssemblyCache(
    out IAssemblyCache ppAsmCache, int reserved);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我刚刚检查了 Create 和 Query 方法的定义,你的正确它们都返回整数。 (2认同)