无法转换类型异常的 COM 对象 [英] Unable to cast COM object of type exception

查看:27
本文介绍了无法转换类型异常的 COM 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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:

无法将System.__ComObject"类型的 COM 对象转换为接口类型IMyInterface".此操作失败,因为 IID 为{GUID}"的接口的 COM 组件上的 QueryInterface 调用因以下错误而失败:不支持此类接口

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?

推荐答案

这个讨厌的、讨厌的异常是由一个称为 COM 编组的概念引起的.问题的本质在于,为了从任何线程使用 COM 对象,该线程必须能够访问描述 COM 对象的类型信息.

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();
}

基本上,上面的声明指示 .NET 框架 COM 加载器使用传统技术从注册表加载类型信息,并定位关联的类型库并从那里开始.

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.

您还应该将 COM 对象的创建限制为单个线程(以防止线程编组)以帮助解决此问题.

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

总而言之,此错误与类型信息和线程编组有关.确保每个想要访问 COM 对象的线程都有相关信息,以便从源线程中解组对象.

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:这个问题在 .NET 4.0 中使用一种叫做类型等效"的技术解决

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

这篇关于无法转换类型异常的 COM 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆