從 C++ 編寫 DLL 到 C# 調用的完整流程,含導出宏定義、extern "C" 防止名字修飾、目錄結構安排、C# DllImport 屬性設置。
#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
Solution/
├── CppDll/ (C++ DLL 專案)
│ └── Debug/
│ └── DLLTest.dll
└── CSharpApp/ (C# 控制台專案)
└── bin/Debug/
└── CSharpApp.exe

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);
}
}
__cdecl,C# 需顯式指定 CallingConvention.Cdecl,否則棧平衡錯誤。CharSet = CharSet.Ansi 或 Unicode,並加 [MarshalAs(UnmanagedType.LPStr)]。DllImport("DLLTest.dll")。Prefer 32-bit 勾選狀態需與 DLL 位數一致,否則 BadImageFormatException。