Groups | Blog | Home
all groups > dotnet interop > march 2007 >

dotnet interop : Marshal.GetTypedObjectForIUnknown and reference counts


Michael Phillips, Jr.
3/23/2007 10:52:01 AM
Per the MSDN documentation, the object returned is a runtime callable
wrapper.

The runtime callable wrapper maintains and releases the interface pointers.
See:
http://msdn2.microsoft.com/en-us/library/8bwh56xe.aspx

[quoted text, click to view]

Steve
3/23/2007 12:30:00 PM
Hello,

Say I have an interface from IUnknown::QueryInterface that I want
available in my .Net program. When QueryInterface returns, I am
responsible for Release()ing it, but depending on whether
GetTypedObjcetForIUnknown has already wrapped that object, it may or may
not increase the reference count on the COM object. How do I know when
Michael Phillips, Jr.
3/26/2007 11:09:55 AM
COM rules always apply.

For unmanaged COM objects, you are responsible for the reference count
bookeeping per the COM guidelines.

For managed COM objects that use the RCW mechanism, the RCW handles the
reference count bookeeping per the COM guidelines.


[quoted text, click to view]
Steve
3/26/2007 3:11:10 PM
Yes, I realise that. But consider this:

- IUnknown::QueryInterface returns an IntPtr to an interface. The
reference count is 1.
- GetTypedObjectForIUnknown is called to generate a RCW. It generates a
new RCW, now the reference count is 2.
- I use Marshal.ReleaseComObject to release the original reference.

That's all fine. We have 1 reference to the interface, that of the RCW.
Now consider this situation.

- IUnknown::QueryInterface returns an IntPtr to an interface. The
reference count is N.
- GetTypedObjectForIUnknown is called to generate a RCW. It has already
generated a RCW for this object in the past so the reference count is
unchanged.
- I use Marshal.ReleaseComObject to release the original reference. This
decreases the count back to N-1, prematurely freeing the object.

Am I misunderstanding something fundamental here?

Regards
Steve


[quoted text, click to view]
AddThis Social Bookmark Button