簡體   English   中英

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

[英]IntPtr.ToInt32() Marshal.ThrowExceptionForHR() - Querying the GAC

我一直在使用我在網上找到的一些代碼來使用Fusion.dll查詢GAC,但是最近我又收到一些錯誤報告,抱怨OverflowException。

    // 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;
    }

令人討厭的代碼是當它試圖將IntPtr實際轉換為Int64時將其轉換為Int32,但問題是Marshal.ThrowExceptionForHR僅接受一個I​​nt32,所以我對於執行該操作有些困惑。 目前,我只是在處理異常,但我想知道正確的處理方式是什么?

馬龍

為什么要使用IntPtr來保存HRESULT的值? HRESULT的大小與平台無關,始終為32位,因此您應使用intuint來保存該值。 更改代碼以改為使用其中之一,問題將消失。

檢查DllImportCreateAssemblyCache簽名。 看起來應該是int ,而不是IntPtr

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM