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

C# 調用 C++ DLL 完整實戰:聲明、導出、目錄結構與 P/Invoke

     編輯:關於C語言

從 C++ 編寫 DLL 到 C# 調用的完整流程,含導出宏定義、extern "C" 防止名字修飾、目錄結構安排、C# DllImport 屬性設置。

1. C++ 頭文件

#ifndef _DLLTUT_DLL_H_
#define _DLLTUT_DLL_H_

#if defined DLL_EXPORT
#define DECLDIR __declspec(dllexport)
#else
#define DECLDIR __declspec(dllimport)
#endif

extern "C"
{
    DECLDIR int Add(int a, int b);
    DECLDIR void Function(void);
}
#endif

2. 目錄結構

Solution/
├── CppDll/          (C++ DLL 專案)
│   └── Debug/
│       └── DLLTest.dll
└── CSharpApp/       (C# 控制台專案)
    └── bin/Debug/
        └── CSharpApp.exe

目錄結構示意圖

3. C# 調用代碼

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication30
{
    class Program
    {
        static void Main(string[] args)
        {
            Test.Function();
            Console.WriteLine("Result: " + Test.Add(2, 3));
            Console.ReadLine();
        }
    }

    class Test
    {
        [DllImport("..\\..\\lib\\DLLTest.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void Function();

        [DllImport("..\\..\\lib\\DLLTest.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int Add(int i, int j);
    }
}

關鍵避坑指南

  • CallingConvention:C++ 默認 __cdecl,C# 需顯式指定 CallingConvention.Cdecl,否則棧平衡錯誤。
  • 字符串封送:涉及字符串參數時,使用 CharSet = CharSet.Ansi 或 Unicode,並加 [MarshalAs(UnmanagedType.LPStr)]。
  • DLL 路徑:相對路徑相對於**執行文件目錄**;生產環境建議將 DLL 放入同目錄或系統 PATH,改用 DllImport("DLLTest.dll")。
  • x86/x64 匹配:C# 專案 Prefer 32-bit 勾選狀態需與 DLL 位數一致,否則 BadImageFormatException。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved