C++COM与C#组件的互操作.docxVIP

  • 78
  • 0
  • 约1.66万字
  • 约 15页
  • 2021-01-10 发布于天津
  • 举报
C++环境下按COM方式调用C#组件的方法 1.互操作基础 首先需要声明清楚的是:COM与.NET组件(准确的说,应该叫程序集,Assembly )是两个不同的概念! COM 组件对象模型是微软早期的一种软件复用标准和技术方案,用 IDL语言定义接口,用非托管语言( C++ )定义 类以实现接口功能,编译生成 DLL组件,并生成相应的类型定义库 TLB。而.NET程序集则是一种基于 CLR的 多编程语言无缝集成的软件封装技术。可采用 .NET编程语言(C#,VB.NET )直接定义接口与类,能够简单生 成程序集。编写源代码时按照一定的要求赋予 GUID属性,生成DLL后注册到GAC即可实现共享复用。 Although COM clients can call code that is exposed in a public class by .NET servers, .NET code is not directly accessible to COM clients. In order to use .NET code from a COM client, you need to create a proxy known as a COM callable wrapper (CCW) COM Callable Wrappers ( COM 包装) COM在以下几个重要方面与 .NET Framework理 COM在以下几个重要方面与 .NET Framework 理)、对象实例的获取 (接口指针 QueryInterface / 对象模型存在差异: 生命周期(自己管理/ CLR管 反射)、内存的管理(位置不变/ CLR调整)。 调用.NET 服务器的COM客户端. 调用.NET 服务器的 COM客户端 .调用COM J服驾爭的 1 .met客户端 CCW概览图 通过运行时可调用包装(RCW)访问COM对象 Managed code components not only depend on the CLR, they require the components with which they interact to depend on the CLR. Because COM components dont operate within the CLR, they are unable to call managed code components directly. The unmanaged code simply cannot reach into the CLR to directly call managed components. The way out of this dilemma is to use a proxy(CCW). 2.开发一个面向非托管客户的.NET程序集步骤 要使基于.NET的Class以COM组件的形式对非托管代码可见(可调用),必须要满足 两个基本条件: 一是,必须给Interface 和Class分别添加GUID属性;二是,必须导出程序集对等的 COM类型库TLB 并且在注册表中注册组件信息( 这里的组件即Interop COM ,此组件实际上以托管程序集的形势存在,在被调 用时,由CCW将其实例化为内存中的 COM对象并管理其生存周期与内存释放 )。 创建.NET程序集的大致步骤如下: 定义接口,并创建类以实现接口功能。添加引用: using System.Runtime.lnteropServices; using System.Windows.Forms; 在类与接口定义前分别添加 GUID属性,代码如下 [Guid(03AD5D2D-2AFD-439f-8713-A4EC0705B4D9)] 在类定义前添加属性[Classlnterface(ClasslnterfaceType.None)] 。 设置[assembly: ComVisible(true)] 使得对 COM 可见(重要!) 给程序集添加版本属性;添加强命名 Key(非必须); [非必须步骤]将程序集添加到公用程序集缓冲区。 Install the .NET assembly into the Global Assembly Cache (GAC) so that it will be available as a shared assembly. To install an assembly into the GAC, use the gacutil tool: gacutil /i YourNETServer.dll 从生成的DLL类库中导出类型库(type library, TLB ),并注册COM组件

文档评论(0)

1亿VIP精品文档

相关文档