Unable to cast COM object of type exception

I've been developing a C# application which uses 7-zip through COM interfaces. I ran into this funny thing where I was able to extract archives from a worker thread in one instance, but not another, getting this same exception.

I found that, so long as you initialize the offending COM object in the thread where it is used no exception is thrown. My solution was to dispose the objects which utilized COM interfaces and re-initialize them when passing them between threads.


I got an advice and it helped me!

Find in the main thread (Program.cs) the line [STAThread] and change it to [MTAThread].


This nasty, nasty exception arises because of a concept known as COM marshalling. The essence of the problem lies in the fact that in order to consume COM objects from any thread, the thread must have access to the type information that describes the COM object.

In your scenario described, the reason it fails on the second thread is because the second thread does not have type information for the interface.

You could try adding the following to your code:

[ComImport]
[Guid("23EB4AF8-BE9C-4b49-B3A4-24F4FF657B27")]
public interface IMyInterface
{
    void CallMethod();
}

Basically the declaration above instructs the .NET framework COM loader to load type information using traditional techniques from the registry and locate the associated type library and go from there.

You should also restrict the creation of the COM object to a single thread (to prevent thread marshalling) to help solve this issue.

To summarize, this error revolves around type information and thread marshalling. Make sure that each thread that wants to access the COM object has the relevant information to unmarshal the object from the source thread.

PS: This problem is solved in .NET 4.0 using a technique called "Type Equivalence"

Tags:

C#

Interface

Com