tags:

views:

95

answers:

2

Is it possible to increase the RCW reference count on an unknown interface? (i.e. not the reference count on the underlying COM object)

I have some old COM server code

int Method1(object comobject) {
    try {
        // do something with comobject
        return 0;
    }
    finally {
        Marshal.ReleaseComObject(comobject);
    }
 }

This code works fine but now I need to call it from another method.

int Method2(object comobject) {
    int result = Method1(comobject);
    // Do something with combject
}

The type of comobject will vary (that is why it is object)

+1  A: 

The RCW proxy is a .NET object. Any live reference to it will block the GC from collecting it.

There is no reference count for .NET types.

Richard
In the documentation for ReleaseComObject it says:"The RCW has a reference count that is incremented every time a COM interface pointer is mapped to it. The ReleaseComObject method decrements the reference count of an RCW. When the reference count reaches zero, the runtime releases all its references on the unmanaged COM object"
adrianm
@adrianm: Read further through the remarks, and note there is no "UnreleaseComObject" to increment the count. .NET via an RCW holds a single reference to the COM object, however many references there are to the RCW (as .NET uses a collecting GC rather than reference counting).
Richard
@Richard: I don't want to increase the reference count on the COM object. Just want to create a copy of the existing RCW that I can send to Method1 above (so two ReleaseComObject/Finalizers are needed to free the com object)
adrianm
@adrianm: Don't call `ReleaseComObject` in `Method1` (generally `ReleaseComObject` should only be used if you have to force COM object destruction *now*: but you have to deal with the consequences).If you can't change `Method1`, perhaps you should re-create it without the lifetime ending.
Richard
+1  A: 

There's the Marshal.AddRef() method, wrong reference count change though. I'm pretty sure incrementing the RCW count directly is not possible. Dig yourself out of the deep hole you're in and fix the old code.

Hans Passant