首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 托管代碼與 C++ 非托管代碼互相調用(一):C# 調用 C++ DLL

     編輯:關於C語言

背景

專案核心演算法需防反編譯,決定以 C++ 實作核心邏輯編譯為 DLL,C# 負責 UI 與資料存取,透過 P/Invoke 調用。

C++ DLL 建立 (靜態連結)

  1. 建立 VC++ 專案:Win32 Console → DLL。
  2. CppDemo.cpp 實作導出函式:

extern "C" __declspec(dllexport) int Add(int a, int b)
{
    return a + b;
}
  1. 編譯產生 CppDemo.dll。

C# 呼叫端

  1. 建立 Console 專案 InteropDemo。
  2. 引用 System.Runtime.InteropServices。
  3. 使用 DllImport 靜態導入:

using System;
using System.Runtime.InteropServices;

namespace InteropDemo
{
    class Program
    {
        [DllImport("CppDemo.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
        public static extern int Add(int a, int b);

        static void Main(string[] args)
        {
            Console.WriteLine(Add(1, 2)); // 輸出 3
            Console.Read();
        }
    }
}

關鍵點

  • extern "C":防止 C++ 名稱修飾,確保導出名稱即為 Add。
  • CallingConvention.Cdecl:符合 C++ 預設呼叫慣例。
  • 將 CppDemo.dll 放置於 C# 專案輸出目錄 (bin/Debug) 或系統 PATH 路徑。
  • 此為靜態載入 (Load-time dynamic linking),啟動時即載入 DLL。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved