專案需求:使用 C# 快速構建 UI 介面,核心邏輯以 C++ 實現。兩者如何高效互通?最佳路徑是 C++/CLI (托管 C++) 封裝非托管 C++ 為 DLL,C# 專案直接引用該 DLL。
+----------------+ +------------------------+ +------------------+
| C# UI (exe) | <---> | C++/CLI Wrapper (dll) | <---> | Native C++ Lib |
| (Managed) | | (Mixed Mode) | | (Unmanaged) |
+----------------+ +------------------------+ +------------------+
.lib 或 .dll)。CLR Class Library,專案屬性啟用 /clr。.h/.cpp 中定義 public ref class,內部持有原生指標,提供給 C# 呼叫的方法。
// Wrapper.h
#pragma once
#include "NativeCore.h"
using namespace System;
namespace Wrapper {
public ref class CoreWrapper {
NativeCore* _native;
public:
CoreWrapper() { _native = new NativeCore(); }
~CoreWrapper() { delete _native; }
int Calculate(int a, int b) { return _native->Calculate(a, b); }
};
}
Wrapper.dll。using Wrapper;
var core = new CoreWrapper();
int result = core.Calculate(3, 5);
IDisposable 或析構函數,確保原生資源釋放。Wrapper.dll、NativeCore.dll、msvcrxxx.dll 等運行時。此方案在 VS2013/2015/2019/2022 均完美支援,是 C# 與 C++ 混合開發的標準最佳實踐。