Marshal.Release() 的 ReportAvOnComRelease 错误

ReportAvOnComRelease Error with Marshal.Release()

我在这里看到过类似的错误,但不能完全确定是什么原因造成的。

我有一个 IntPtr 引用了一个 GetForegroundWindow() 对象:

IntPtr ptr = GetForegroundWindow();

这个GetForegroundWindow()方法是这样的:

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

这又用来建立GetExecutablePath()方法:

string name = GetExecutablePath(ptr);

过了这样的时间我打电话给臭名昭著的Marshal.Release()

Marshal.Release(ptr);

此时我收到以下错误:

Managed Debugging Assistant 'ReportAvOnComRelease' has detected

更多信息包括:

Additional information: An exception was caught but handled while releasing a COM interface pointer through Marshal.Release, Marshal.ReleaseComObject or implicitly after the corresponding RuntimeCallableWrapper was garbage collected. This is the result of a user refcount error or other problem with a COM object's Release. Make sure refcounts are managed properly. While these types of exceptions are caught by the CLR, they can still lead to corruption and data loss so if possible the issue causing the exception should be addressed

对我来说,这表明内存泄漏或指针损坏的可能性非常高。

我似乎无法确定原因,但正如您从极其简单和直接的用例中看到的那样。

关于如何调试和/解决此问题的任何建议?

你对COM的概念很模糊。你没有使用任何东西,这是普通的 pinvoke。 MDA 正确地告诉您,您所做的没有任何意义。

Marshal.Release() 仅用于减少 COM 接口指针上的引用计数。不是 window 句柄。 window 的生命周期由用户或创建 window 的线程控制。所以你不能尝试 "release" GetForegroundWindow() 的 return 值。

只需删除 Marshal.Release()。