1. 程式人生 > >C#託管程式碼與C++非託管程式碼互相呼叫1

C#託管程式碼與C++非託管程式碼互相呼叫1

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

一. C# 中靜態呼叫C++動態連結

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

2. 在DllDemo.cpp檔案中新增這些程式碼。
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新增如下程式碼: 
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
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");

詳細請參見程式碼

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++寫的程式碼了.