IntPtr.ToInt32() Marshal.ThrowExceptionForHR() - 查询 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 转换为 Int32 时,而它实际上是 Int64,但问题是 Marshal.ThrowExceptionForHR 只接受 Int32,所以我有点不知道该怎么做。目前我正在处理异常,但我想知道正确的方法是什么?
马龙
I've been using some code I've found on the net to query the GAC using the fusion.dll however I've recently been getting a few error reports back complaining of an 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;
}
The offending code is when its trying to convert the IntPtr to a Int32 when its actually an Int64, but the problem is the Marshal.ThrowExceptionForHR only accepts an Int32 so I'm a bit stuck for what to do. At the moment I'm just handling the exception but I'd like to know what is the correct way of doing it?
Marlon
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查
DllImport
上CreateAssemblyCache
的签名。看起来应该是int
,而不是IntPtr
Check the signature on your
DllImport
forCreateAssemblyCache
. It looks like it should beint
, notIntPtr
为什么使用
IntPtr
来保存 HRESULT 的值? HRESULT 的大小与平台无关,它始终为 32 位,因此您应该使用int
或uint
来保存该值。更改代码以使用其中之一,问题就会消失。Why are you using an
IntPtr
to hold the value of an HRESULT? The size of an HRESULT is not platform dependent, it is always 32 bits, so you should use eitherint
oruint
to hold the value. Change the code to use one of these instead, and the problem will go away.