0

For certain reasons, I must provide manually written runtime callable wrappers for a number of COM components offered by my shop.

This is the interface definition for component A:

[ComImport, Guid("02922621-2EAE-4442-8A0A-C1C3CD886027")]
public interface IProdistLogging
{
  [DispId(1000)]
  IProdistLoggingHierarchy CreateHierarchy ([MarshalAs(UnmanagedType.BStr)] string type, object configuration);
}

This is the interface definition for component B:

[ComImport, Guid("8D841E5C-F25B-4C12-B03A-70A899B3A32E")]
public interface ISts
{
  [DispId(1001)]
  IProdistLoggingHierarchy Logging { get; set; }

  [DispId(1000)]
  IStsSession CreateSession ();
}

This is the interface definition for component C:

[ComImport, Guid("13385FC6-2618-4830-A3A9-703398AA5A0B")]
public interface IStsRsfn
{
  [DispId(1000)]
  ISts Sts { get; set; }

  [DispId(1010)]
  IStsRsfnSession CreateSession();
}

Now, the following test program terminates with an InvalidCastException:

public static void Main (string[] args)
{
  IProdistLogging logging = (IProdistLogging)System.Activator.CreateInstance(Type.GetTypeFromProgID("prodist.logging.Logging.5.4"));
  IProdistLoggingHierarchy loggingHierarchy = logging.CreateHierarchy("log4cxx", null);
  ISts sts = (ISts)System.Activator.CreateInstance(Type.GetTypeFromProgID("prodist.sts.Sts.5.4"));
  sts.Logging = loggingHierarchy;
  IStsRsfn rsfn = (IStsRsfn)System.Activator.CreateInstance(Type.GetTypeFromProgID("prodist.sts.rsfn.StsRsfn.5.4"));

  // The following statement raises an InvalidCastException
  // with message "Specified cast is not valid"
  rsfn.Sts = sts;

  IStsRsfnSession session = rsfn.CreateSession();
  return;
}

Why would this be?

Edit 1: this is the result of toString() on the exception object:

System.InvalidCastException: Specified cast is not valid.
   at prodist.sts.rsfn.IStsRsfn.set_Sts(ISts value)
   at sandbox.Program.Main(String[] args) in (...)
4

1 回答 1

0

从那以后,我们发现了解释上述症状的缺失信息:接口的实际 IDL 定义。

有问题的 .NET 包装器没有包含相应接口的所有方法,因此 IDL 和 .NET 中 Sts put 属性的序号索引不一样——即使 DispId 值是正确的。

在我们更新 .NET 包装器以完全反映 IDL 定义中的所有方法之后——使得每个方法与另一个方法位于相同的序号索引处——一切正常。

程序员假设方法根据 DispId 属性的值“偏移”,但似乎它们在方法列表中的实际位置从第一个到最后一个“偏移”。这意味着为接口提供部分包装器是非法的——省略某些方法的包装器。

于 2015-07-06T18:00:06.473 回答