2010-12-09 37 views
1

我一直在使用我在網上找到的一些代碼來使用fusion.dll查詢GAC,但是我最近得到了一些錯誤回報抱怨OverflowException。IntPtr.ToInt32()Marshal.ThrowExceptionForHR() - 查詢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; 
    } 

有問題的代碼是當其試圖將IntPtr的轉換成的Int32當它實際上是一個Int64的,但問題是Marshal.ThrowExceptionForHR只接受一個I​​nt32,所以我堅持了什麼,做了一下。目前我只是處理異常,但我想知道做這件事的正確方法是什麼?

馬龍

+0

您的測試是錯誤太多,一個HRESULT是僅當值<0 – 2010-12-09 18:04:47

回答

4

檢查DllImport上的簽名CreateAssemblyCache。它看起來像它應該是int,不IntPtr

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

你爲什麼要使用IntPtr舉行的HRESULT的價值? HRESULT的大小不依賴於平臺,它始終爲32位,因此您應該使用intuint來保存該值。更改代碼以使用其中一種代碼,問題就會消失。

+0

assemblyCache.QueryAssemblyInfo()返回一個IntPtr一個錯誤代碼。我的基本類型知識是生鏽的,如果我將它轉換爲uInt意味着我會有兩倍的範圍(正數),並且它不會溢出? - 剛剛嘗試過,不幸的是,元帥方法期望@Marlon Int32 – Marlon 2010-12-09 17:12:06

+0

- 這是我的觀點;它不應該是因爲這是代表HRESULT的錯誤類型。你應該改變它,所以它是正確的。 – 2010-12-09 17:13:49