如何:在本机类型中保存对值类型的引用

更新:2007 年 11 月

在已装箱的类型上使用 gcroot,以便在本机类型中保存对值类型的引用。

示例

// reference_to_value_in_native.cpp
// compile with: /clr
#using <mscorlib.dll>
#include <vcclr.h> 

using namespace System; 

public value struct V {
   String ^str;
};

class Native {
public:
   gcroot< V^ > v_handle;
};

int main() {
   Native native;
   V v;
   native.v_handle = v;
   native.v_handle->str = "Hello";
   Console::WriteLine("String in V: {0}", native.v_handle->str);
}

String in V: Hello

请参见

参考

使用 C++ Interop(隐式 PInvoke)