资源管理code调用SHCreateItemFromParsin

资源管理code调用SHCreateItemFromParsin

本文介绍了我是否需要免费的资源管理code调用SHCreateItemFromParsingName什么时候?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 code

[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
static extern void SHCreateItemFromParsingName(
[In][MarshalAs(UnmanagedType.LPWStr)] string pszPath,
[In] IntPtr pbc,
[In][MarshalAs(UnmanagedType.LPStruct)] Guid iIdIShellItem,
[Out][MarshalAs(UnmanagedType.Interface, IidParameterIndex = 2)] out IShellItem iShellItem);


[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
interface IShellItem
{
}

要使用此功能:

IShellItem iShellItem = null;
Guid iIdIShellItem = new Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe");
SHCreateItemFromParsingName(sourceFile, IntPtr.Zero, iIdIShellItem, out iShellItem);

它的伟大工程,我用它后获得OS图标位图。我的问题是:

It works great, and I use it to get OS icon bitmaps later. My question is:

我需要释放任何资源?一些能告诉我怎么样?

Do I need to free any resource? Could some tell me how?

在此先感谢。

推荐答案

的IShellItem是一个COM接口。您声明它与[ComImport]属性保证了CLR创建一个包装它,一个RCW(运行时可调用包装)。这是周围的原生接口的托管包装。的RCW的行为如同一般的.NET类,它们是由垃圾收集管理。具有完全相同的规则,迟早垃圾收集器看到,你的程序不具有参考RCW了。并提出在终结队列中。该RCW的终结调用的IUnknown :: Release()方法,并且破坏了原生的COM对象。

IShellItem is a COM interface. Your declaration of it with the [ComImport] attribute ensures that the CLR creates a wrapper for it, an RCW (Runtime Callable Wrapper). Which is a managed wrapper around the native interface. RCWs behave just like regular .NET classes, they are managed by the garbage collector. With the exact same rules, sooner or later the garbage collector sees that your program doesn't have a reference to the RCW anymore. And puts in on the finalizer queue. The RCW's finalizer calls the IUnknown::Release() method and that destroys the native COM object.

在换句话说,它是自动的,就像.NET对象

In other words, it is automatic, just like .NET objects.

您在技术上可以通过调用Marshal.ReleaseComObject的赶紧沿()。这大致相当于IDisposable.Dispose(),是的RCW没有实现,因为它是如此难以看到COM接口指针间接引用的方法。使用它,是要拍你的脚虽然与行为不端的地方有没有任何影响,因为你错过了一个参考,以已被分开与其基础RCW的COM对象不能用崩溃您的程序它的一个很好的方式。只是不需要一个简单的shell项目的参考,尤其是当你快吃了。

You technically can hurry it along by calling Marshal.ReleaseComObject(). It is roughly equivalent to IDisposable.Dispose(), a method that RCWs don't implement because it is so difficult to see indirect references on COM interface pointers. Using it is a good way to shoot your foot though, with misbehavior somewhere between it having no effect at all because you missed a reference and crashing your program with "COM object that has been separated from its underlying RCW cannot be used". Just not needed for a simple shell item reference, especially when you consume it quickly.

这篇关于我是否需要免费的资源管理code调用SHCreateItemFromParsingName什么时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:04