C#Managed 程式碼與C++Unmanaged 程式碼互相調用二(C++調用C#代碼)

來源:互聯網
上載者:User

上篇文章提到,目前項目想做到核心部分代碼不被反編譯,而考慮到團隊成員都是比較熟悉C#,因此 核心演算法部分採用C++,而其他地方則採用C#(例如資料訪問層,介面層都使用C#語言)。在上一篇文章 中完成了C#Managed 程式碼調用C++Unmanaged 程式碼,現在接著完成第二部分,即C++Unmanaged 程式碼調用C#Managed 程式碼,分 為兩部分,首先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;
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;
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.