C# 開發COM組件供c++使用

來源:互聯網
上載者:User

標籤:opera   framework   c++引用   create   uid   安裝   執行個體化   管理員   amp   

C# 開發COM組件供c++使用

 

Microsoft在解決和以往的COM和SDK開發技術之間的互通性(Interoperability)方面做了很多的工作,其中包括COM和.NET對象之間的相互調用以及.NET如何調用SDK中的Windows庫函數。

本文在學習網上資料的基礎上,實現用C#開發組件供C++使用的過程。

 

編程環境:vs2015 (COM組件) vs2005 c++調用 作業系統 win10

 

一.C#COM組件

1.建立一個C#類庫項目:ExcelCom  (原計劃做一個EXCEL的com)

 

2.在項目中添加介面

C++調用com組件中所有的功能只能通過介面來調用,不能直接調用類或函數

 

 

Guid可通過 Tool -> 建立GUID產生

 

介面DoExcel的編寫

    public interface DoExcel    {        [DispId(1)]  //如果需要添加其他函數,繼續加 [DispId(2)]  ...        int Plus(int a, int b);    }

 

3.添加一個ExcelOperate類繼承介面DoExcel

using System.Runtime.InteropServices;

 

 

 

4. 修改AssemblyInfo.cs檔案中[assembly: ComVisible(false)]

 

 

項目->屬性->產生下 選中"為COM互操作註冊“

 

 

5.產生解決方案

產生解決方案,成功才可。產生的檔案ExcelCom.dll檔案。

6.COM註冊

COM 註冊後才能使用。

註冊過程:管理員身份運行cmd.進入C:\Windows\Microsoft.NET\Framework\v2.0.50727

注意:自己系統上安裝的.net版本

輸入”RegAsm D:\CAAProj\ExcelCom\ExcelCom\bin\Debug\ExcelCom.dll /tlb:ExcelCom.tlb /codebase“

 

 

COM卸載與註冊過程基本相同,只需將命令改為

“RegAsm  /u  D:\CAAProj\ExcelCom\ExcelCom\bin\Debug\ExcelCom.dll  /tlb: COMLib.tlb  /codebase”

 

提示成功註冊後,及可在C++上引用了(可在項目目錄下是否成功產生了ExcelCom.tlb檔案)

 

二.C++引用COM組件

1.建立一個C++程式(控制台程式即可),本例中是ExcelComDemo

2.將ExcelCom.tlb拷貝到ExcelComDemo下的ExcelComDemo檔案中。

3.建立一個調用代碼

#include "stdafx.h"#include <Windows.h>#include <string.h>#include <iostream>using namespace std;#import "ExcelCom.tlb" named_guids raw_interface_only int _tmain(int argc, _TCHAR* argv[]){CoInitialize(NULL);ExcelCom::DoExcelPtr  ptr;  //介面ptr.CreateInstance(ExcelCom::CLSID_ExcelOperate);//執行個體化一個類 CLSID_ 類名long a = 1;long * lPtr = &a;long AA = ptr->Plus(1,2);cout<<AA<<endl;        system("pause");return 0;} 

 

4.運行後執行結果如下:

 

 

 

C# 開發COM組件供c++使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.