现在接着完成第二部分,即C++非托管代码调用C#托管代码,分为两部分,首先C#建立COM+组件,其次是C++调用COM+组件。 C#建立COM+组件 1. 在VS中,新建类库ComInterop 2. 在类库新增接口:ComInteropInterface, 及相应的实现ComInterop, ComInterop同时必须继承自ServicedComponent。ComInteropInterface中有两个简单接口: int Add(int a, int b); int Minus(int a, int b); 具体代码如下: using System;
[DispId(2)]
public int Add(int a, int b) public int Minus(int a, int b) 3 . 使用REGASM命令导出虚拟表,当重新编译生产Dll时需要使用REGASM /u命令将前一次Dll注销 REGASM ComInteropDemo.dll /tlb ComInteropDemo.tlb REGASM /u ComInteropDemo.dll 首先对COM+组件的写法需要注意以下几点: 2. 方法和属性必须在接口中声明,事件也必须在事件接口中声明. 否则将在VC中无法调用,在接口中声明主要是为了在COM 中的vtab中. 3. 必须对接口中的方法,属性,事件前声明[DispId(1)] 5. 而且项目一定需要是COM Interop,并且具有强命名 6. 组件ComVisible属性必须为true,这里强调的原因是VS中默认值为false C++调用C# COM+组件 步骤: 1. 建立C++ 项目CppLoader,项目类型选择Win32,控制台应用程序 2. 在头文件中导入类型库tlb #import "..\Debug\ComInteropDemo.tlb" 3. 初始化COM以及产生智能指针(一般是在需要调用COM组件中提供的方法时就需要产生指向该接口的智能指针) 4. 调用COM中的方法Add 5. 释放环境 ,具体代码如下 #include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[]) //ComInteropDemo::ComInterop *p;
//创建智能指针ComInteropDemo::ComInteropInterface //创建实例 if(hr == S_OK) CoUninitialize (); |