Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addref on COM RCW

Tags:

com

rcw

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)

like image 369
adrianm Avatar asked Apr 22 '10 10:04

adrianm


2 Answers

There is a way, the RCW count counts how many times the object has been marshaled you can increase this number by performing an additional marshal.

public static T AddRcwRef<T>(T t) 
{
    IntPtr ptr = Marshal.GetIUnknownForObject(t);
    try {
        return (T)Marshal.GetObjectForIUnknown(ptr);
    }
    finally {
         Marshal.Release(ptr); // done with the IntPtr
    }
}

I'm not sure I would recommend using this method, it's probably better to try and get rid of your ReleaseComObject calls.

For further reading, see this blog post on the subject I wrote.

like image 88
Motti Avatar answered Sep 22 '22 06:09

Motti


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.

like image 29
Hans Passant Avatar answered Sep 25 '22 06:09

Hans Passant