Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

c# - Unable to cast COM object of type exception

I have the following code:

public void Test(IMyInterface iInterface)
{
  iInterface.CallMethod ( );
}

Which works fine. However, if I change the code to be threaded:

private IMyInterface myInterface;
public void Test(IMyInterface iInterface)
{
  myInterface = iInterface;
  new Thread ( new ThreadStart ( CallInterfaceMethod) ).Start ( );
}

public void CallInterfaceMethod ( )
{
  myInterface.CallMethod ( )
}

When i use the thread I receive the exception:

Unable to cast COM object of type 'System.__ComObject' to interface type 'IMyInterface'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{GUID}' failed due to the follow error: No such interface supported

But the interface should be supported just fine? Anyone have any thoughts on what is going on here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...