天天看點

C#托管代碼與C++非托管代碼互相調用

http://www.cnblogs.com/Jianchidaodi/archive/2009/03/11/1407270.html#1473515

http://www.cnblogs.com/Jianchidaodi/archive/2009/03/11/1408661.html

C#托管代碼與C++非托管代碼互相調用一(C#調用C++代碼&.net 代碼安全)

在最近的項目中,牽涉到項目源代碼保密問題,由于代碼是C#寫的,容易被反編譯,是以決定抽取核心算法部分使用C++編寫,C++到目前為止好像還不能被很好的反編譯,當然如果你是反彙編高手的話,也許還是有可能反編譯。這樣一來,就涉及C#托管代碼與C++非托管代碼互相調用,于是調查了一些資料,順便與大家分享一下:源代碼下載下傳

一. C# 中靜态調用C++動态連結

    1. 建立VC工程CppDemo,建立的時候選擇Win32 Console(dll),選擇Dll。

    2. 在DllDemo.cpp檔案中添加這些代碼。

Code

extern "C" __declspec(dllexport) int Add(int a,int b)

{

     return a+b;

}

    3. 編譯工程。

    4. 建立新的C#工程,選擇Console應用程式,建立測試程式InteropDemo

    5. 在Program.cs中添加引用:using System.Runtime.InteropServices;

    6. 在pulic class Program添加如下代碼:

Code

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.InteropServices;

namespace InteropDemo

{

    class Program

    {

        [DllImport("CppDemo.dll", EntryPoint = "Add", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]

        public static extern int Add(int a, int b); //DllImport請參照MSDN

        static void Main(string[] args)

        {

            Console.WriteLine(Add(1, 2));

            Console.Read();

        }

    }

}

   好了,現在您可以測試Add程式了,是不是可以在C# 中調用C++動态連結了,當然這是靜态調用,需要将CppDemo編譯生成的Dll放在DllDemo程式的Bin目錄下

二. C# 中動态調用C++動态連結

在第一節中,講了靜态調用C++動态連結,由于Dll路徑的限制,使用的不是很友善,C#中我們經常通過配置動态的調用托管Dll,例如常用的一些設計模式:Abstract

Factory, Provider,

Strategy模式等等,那麼是不是也可以這樣動态調用C++動态連結呢?隻要您還記得在C++中,通過LoadLibrary,

GetProcess,

FreeLibrary這幾個函數是可以動态調用動态連結的(它們包含在kernel32.dll中),那麼問題迎刃而解了,下面我們一步一步實驗

    1.  将kernel32中的幾個方法封裝成本地調用類NativeMethod

Code

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.InteropServices;

namespace InteropDemo

{

    public static class NativeMethod

    {

        [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]

        public static extern int LoadLibrary(

            [MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);

        [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]

        public static extern IntPtr GetProcAddress(int hModule,

            [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

        [DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]

        public static extern bool FreeLibrary(int hModule);

    }

}

    2. 使用NativeMethod類動态讀取C++Dll,獲得函數指針,并且将指針封裝成C#中的委托。原因很簡單,C#中已經不能使用指針了,如下         

            int hModule = NativeMethod.LoadLibrary(@"c:"CppDemo.dll");

            IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "Add");

詳細請參見代碼

Code

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.InteropServices;

namespace InteropDemo

{

    class Program

    {

        //[DllImport("CppDemo.dll", EntryPoint = "Add", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]

        //public static extern int Add(int a, int b); //DllImport請參照MSDN

        static void Main(string[] args)

        {

            //1. 動态加載C++ Dll

            int hModule = NativeMethod.LoadLibrary(@"c:\CppDemo.dll");

            if (hModule == 0) return;

            //2. 讀取函數指針

            IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "Add");

            //3. 将函數指針封裝成委托

            Add addFunction = (Add)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(Add));

            //4. 測試

            Console.WriteLine(addFunction(1, 2));

            Console.Read();

        }

        /// <summary>

        /// 函數指針

        /// </summary>

        /// <param name="a"></param>

        /// <param name="b"></param>

        /// <returns></returns>

        delegate int Add(int a, int b);

    }

}

通過如上兩個例子,我們可以在C#中動态或者靜态的調用C++寫的代碼了,找了半天好像沒看到可以上傳源代碼的地方,不過代碼比較清楚了,需要的朋友可以留個郵箱,源代碼下載下傳

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);

具體代碼如下:

Code

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;

        }

    }

}

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++非托管代碼互相調用