How to use Marshal.ReleaseComObject with native Win32 functions

I play with these two native win32 features:

[DllImport( "oleacc.dll" )] public static extern int AccessibleObjectFromWindow( IntPtr hwnd, int dwObjectID, ref Guid refID, ref Accessibility.IAccessible ppvObject ); [DllImport( "oleacc.dll" )] public static extern uint AccessibleChildren( Accessibility.IAccessible paccContainer, int iChildStart, int cChildren, [Out] object[] rgvarChildren, out int pcObtained ); 

And it's hard for me to understand if I need / I need to call Marshal.ReleaseComObject for any of the returned objects. I would appreciate it if someone could enlighten me on this topic! Here's a usage example:

  Accessibility.IAccessible test( int hWnd, string accessName ) { Guid guidCOM = new Guid( 0x618736E0, 0x3C3D, 0x11CF, 0x81, 0xC, 0x0, 0xAA, 0x0, 0x38, 0x9B, 0x71 ); Accessibility.IAccessible a = null; AccessibleObjectFromWindow( new IntPtr( hWnd ), -4, ref guidCOM, ref a ); object[] children = new object[a.accChildCount]; int z; AccessibleChildren( a, 0, children.Length, children, out z ); foreach ( Accessibility.IAccessible a2 in children ) try { if ( a2.get_accName( 0 ) == accessName ) return a2; } catch { } return null; } 
+7
c # interop com
source share
1 answer

Marshal.ReleaseComObject is useful work if you really need the GC to immediately apply the release, instead of waiting for the GC to complete. It’s better not to use it if you really need it, because it tends to capture your code, and you should use it everywhere, including the places where you created the implicit links.

I suspect that the best way for COM interoperability in .Net is to write strongly typed wrapper classes around the methods you use. Thus, there is no way to enter implicit links, and this will simplify the code and ensure the availability of interfaces for the GC. Some of my orc cows reported improved memory using these methods - objects are released on time, as the GC works without leaving any links to secrets.

Generally speaking, all COM objects that are referenced in .Net code are implemented as an RCW object that contains a true link to a COM link β€” calling ReleaseComObject causes RCW to decrease the value of the reference to the counter. Thus, it looks like just calling Release on the actual instance of IUnkown . There is probably no need to make a call in the above example.

+6
source share

All Articles