Addref on COM RCW

Is it possible to increase the counter of RCW links on an unknown interface? (i.e. not counting references to the underlying COM object)

I have an 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 co-object will change (therefore it is an object)

+3
source share
2 answers

There, however, the Marshal.AddRef () method, an invalid reference counter. I am pretty sure that increasing the amount of RCW directly is not possible. Clean yourself out of the deep hole you're in and fix the old code.

0
source

, RCW , , , .

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
    }
}

, , , ReleaseComObject.

. , .

+8

Source: https://habr.com/ru/post/1742258/


All Articles