C#托管代码与C++非托管代码互相调用二(C++调用C#代码)2011-10-17 博客园 Jianchidaodi上篇文章提到,目前项目想做到核心部分代码不被反编译,而考虑到团队成员都是比较熟悉C#,因此 核心算法部分采用C++,而其他地方则采用C#(例如数据访问层,界面层都使用C#语言)。在上一篇文章 中完成了C#托管代码调用C++非托管代码,现在接着完成第二部分,即C++非托管代码调用C#托管代码,分 为两部分,首先C#建立COM+组件,其次是C++调用COM+组件。C#建立COM+组件1. 在VS中,新建类库ComInterop2. 在类库新增接口:ComInteropInterface, 及相应的实现ComInterop, ComInterop同时必须继 承自ServicedComponent。ComInteropInterface中有两个简单接口:int Add(int a, int b);
int Minus(int a, int b); 具体代码如下:using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Runtime.InteropServices; using System.EnterpriseServices;
namespace ComInteropDemo { //接口声明 [Guid("7103C10A-2072-49fc-AD61-475BEE1C5FBB")] public interface ComInteropInterface { [DispId(1)] int Add(int a, int b);
[DispId(2)] int Minus(int a, int b); }
//对于实现类的声明 [Guid("87796E96-EC28-4570-90C3-A395F4F4A7D6")] [ClassInterface(ClassInterfaceType.None)] public class ComInterop : ServicedComponent, ComInteropInterface { public ComInterop() { }
public int Add(int a, int b) { return a + b; }
public int Minus(int a, int b) { return a - b; } } }