description | title | ms.custom | ms.date | helpviewer_keywords | ms.assetid | ||||
---|---|---|---|---|---|---|---|---|---|
Learn more about: How to: Hold Object Reference in Unmanaged Memory | How to: Hold Object Reference in Unmanaged Memory | get-started-article | 11/04/2016 |
| a61eb8ce-3982-477d-8d3d-2173fd57166d |
You can use gcroot.h, which wraps xref:System.Runtime.InteropServices.GCHandle, to hold a CLR object reference in unmanaged memory. Alternatively, you can use GCHandle
directly.
// hold_object_reference.cpp// compile with: /clr #include"gcroot.h"usingnamespaceSystem; #pragma managed classStringWrapper { private: gcroot<String ^ > x; public:StringWrapper() { String ^ str = gcnew String("ManagedString"); x = str; } voidPrintString() { String ^ targetStr = x; Console::WriteLine("StringWrapper::x == {0}", targetStr); } }; #pragma unmanaged intmain() { StringWrapper s; s.PrintString(); }
StringWrapper::x == ManagedString
GCHandle
gives you a means to hold a managed object reference in unmanaged memory. You use the xref:System.Runtime.InteropServices.GCHandle.Alloc%2A method to create an opaque handle to a managed object and xref:System.Runtime.InteropServices.GCHandle.Free%2A to release it. Also, the xref:System.Runtime.InteropServices.GCHandle.Target%2A method allows you to obtain the object reference back from the handle in managed code.
// hold_object_reference_2.cpp// compile with: /clrusingnamespaceSystem;usingnamespaceSystem::Runtime::InteropServices; #pragma managed classStringWrapper { IntPtr m_handle; public:StringWrapper() { String ^ str = gcnew String("ManagedString"); m_handle = static_cast<IntPtr>(GCHandle::Alloc(str)); } ~StringWrapper() { static_cast<GCHandle>(m_handle).Free(); } voidPrintString() { String ^ targetStr = safe_cast< String ^ >(static_cast<GCHandle>(m_handle).Target); Console::WriteLine("StringWrapper::m_handle == {0}", targetStr); } }; #pragma unmanaged intmain() { StringWrapper s; s.PrintString(); }
StringWrapper::m_handle == ManagedString