Addref on COM RCW
Asked Answered
G

2

6

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)

Gibbs answered 22/4, 2010 at 10:16 Comment(0)
E
2

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.

Ecumenism answered 22/4, 2010 at 12:26 Comment(0)
P
12

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.

Pozzuoli answered 6/12, 2010 at 20:45 Comment(0)
E
2

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.

Ecumenism answered 22/4, 2010 at 12:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.