當 C++ 類型較複雜時,托管與非托管類型間的參數轉換(封送)成為核心挑戰。托管擴展雖自動處理基本類型與字串,但深入理解機制對解決疑難雜症至關重要。
托管物件位於 GC 堆,垃圾回收器可能移動物件導致原生指標失效。`__pin` 關鍵字可固定物件位置。框架提供 `PtrToStringChars` 取得固定的原生字元指標:
// vcclr.h 中定義
inline const System::Char* PtrToStringChars(const System::String* s) {
const System::Byte* bp = reinterpret_cast<const System::Byte*>(s);
if (bp != 0) {
unsigned offset = System::Runtime::CompilerServices::RuntimeHelpers::OffsetToStringData;
bp += offset;
}
return reinterpret_cast<const System::Char*>(bp);
}
Visual Studio 2005 引入 C++/CLI(Managed Extensions 2.0),語法與語義全面升級: