Pergunta

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)

Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top