C#托管代码与C++非托管代码互相调用二(C++调用C#代码)
上篇文章提到,目前項目想做到核心部分代碼不被反編譯,而考慮到團隊成員都是比較熟悉C#,因此核心算法部分采用C++,而其他地方則采用C#(例如數據訪問層,界面層都使用C#語言)。在上一篇文章中完成了C#托管代碼調用C++非托管代碼,現在接著完成第二部分,即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);
具體代碼如下:
Codeusing?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;
????????}
????}
}
?
3 . 使用REGASM命令導出虛擬表,當重新編譯生產Dll時需要使用REGASM? /u命令將前一次Dll注銷
??? REGASM? ComInteropDemo.dll /tlb ComInteropDemo.tlb
??? REGASM? /u ComInteropDemo.dll
首先對COM+組件的寫法需要注意以下幾點:
1. 接口,事件,方法,屬性必須是public
2.? 方法和屬性必須在接口中聲明,事件也必須在事件接口中聲明.
???? 否則將在VC中無法調用,在接口中聲明主要是為了在COM 中的vtab中.
3.? 必須對接口中的方法,屬性,事件前聲明[DispId(1)]
4. 每個接口都必須有一個GUID
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. 釋放環境 ,具體代碼如下
Code
#include?"stdafx.h"
#include?<iostream>
using?namespace?std;
#import?"..\\Debug\\ComInteropDemo.tlb"
//路徑一定要正確
int?_tmain(int?argc,?_TCHAR*?argv[])
{
????HRESULT?hr;
????//ComInteropDemo::ComInterop?*p;?
????//初始化COM
????CoInitialize?(?NULL?);????
????//創建智能指針ComInteropDemo::ComInteropInterface
????ComInteropDemo::ComInteropInterfacePtr?ptr;
????//創建實例
????hr?=?ptr.CreateInstance(__uuidof?(ComInteropDemo::ComInterop));
????if(hr?==?S_OK)
????{
????????cout?<<?ptr->Add?(1.0,?2.0);
????}????????
????CoUninitialize?();?
????return?0;
}
?
附件: 源代碼下載, 上一篇文章C#托管代碼調用C++非托管代碼
?
轉載于:https://www.cnblogs.com/Jianchidaodi/archive/2009/03/11/1408661.html
總結
以上是生活随笔為你收集整理的C#托管代码与C++非托管代码互相调用二(C++调用C#代码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TheBeerHouse 网站项目学习笔
- 下一篇: 购物车实例 转载至http://www.