0
  1. 我有 COM 组件 ( dll ) ThirdParty 定义了接口和一些 COM 类 ThirdPartyObjectClass 实现了这个接口。我有适当的文件 ThirdParty.h 和 ThirdParty_i.c 允许在 C++ 中编译它。

       IThirdParty
       {
            HRESULT ComFoo();
       }
    
  2. 我使用“tlbimp /sysarray”构建了名为 ThirdPartyInterop.dll 的互操作 dll,它公开了 .Net 接口 ThirdPartyObject

  3. 我编写了新的 C# 组件,它引用了 ThirdPartyInterop.dll

      using ThirdPartyInterop;
      namespace CsComponent
      {
            public class CsClass
            {
                public void NetFoo( ThirdPartyObject thirdPrty )
                {
                    thirdPrty.ComFoo();
                }
            } 
       }
    

ThirdPartyClass 的元数据是:

   using System.Runtime.InteropServices;

   namespace ThirdPartyInterop
   {
       [CoClass(typeof(ThirdPartyObjectClass))]
       [Guid("xxxx")]
       public interface ThirdPartyObject : IThirdParty
       {
       }
   }

   using System;
   using System.Runtime.InteropServices;

   namespace ThirdPartyInterop
   {
       [TypeLibType(4160)]
       [Guid("yyyy")]
       public interface IThirdParty
       {
           [DispId(1)]
           void ComFoo();
       }
   }

我有一个用托管 C++ 编写的旧代码。

with the following:

   #include "stdafx.h"
   #pragma managed(push, off)
   #include "ThirdParty_i.c"
   #include "ThirdParty.h"
   #pragma managed(pop)

   void CppFoo( IThirdParty* thirdParty )
   {
       ...
       thirdParty -> ComFoo();
       ...
   }

我需要更改它以使用我的 CsClass:

   #include "stdafx.h"
   #pragma managed(push, off)
   #include "ThirdParty_i.c"
   #include "ThirdParty.h"
   #pragma managed(pop)

   void CppFoo( IThirdParty* thirdParty )
   {
       ...
       //thirdParty -> ComFoo();
       CsComponent::CsClass^ csClass = gcnew CsComponent::CsClass();
       csClass.NetFoo( thirdParty );
       ...
   }

但这无法编译:错误 C2664: 'CsComponent::CsClass::NetFoo' : 无法将参数 1 从 'IThirdParty *' 转换为 'ThirdPartyInterop::ThirdPartyObject ^'

以下实现是可以的:

   #include "stdafx.h"
   #pragma managed(push, off)
   #include "ThirdParty_i.c"
   #include "ThirdParty.h"
   #pragma managed(pop)

   void CppFoo( IThirdParty* thirdParty )
   {
       ...
       //thirdParty -> ComFoo();
       CsComponent::CsClass^ csClass = gcnew CsComponent::CsClass();
       ThirdPartyInterop::ThirdPartyObject^ _thirdParty = gcnew ThirdPartyInterop::ThirdPartyObject();
       //csClass.NetFoo( thirdParty );
       csClass.NetFoo( _thirdParty );
       ...
   }

但我需要使用 CppFoo 的参数 thirdParty。

我的问题是:

如何从给定的 IThirdParty* 创建 ThirdPartyInterop::ThirdPartyObject ?

4

1 回答 1

1

因为在您的情况下,每个 IThirdParty 实际上都是一个 ThirdPartyObject,您可以只使用演员表。但是,除了在新指令中,您永远不应该使用 com 对象的具体类型,始终只使用接口。更改您的 NetFoo() 方法以将 IThirdParty 作为参数。

于 2014-07-24T04:49:34.070 回答