방법: 관리되지 않는 메모리에 개체 참조 유지

래핑하는 gcroot.h를 GCHandle사용하여 관리되지 않는 메모리에 CLR 개체 참조를 저장할 수 있습니다. 또는 직접 사용할 GCHandle 수 있습니다.

예제

// hold_object_reference.cpp
// compile with: /clr
#include "gcroot.h"
using namespace System;

#pragma managed
class StringWrapper {

private:
   gcroot<String ^ > x;

public:
   StringWrapper() {
      String ^ str = gcnew String("ManagedString");
      x = str;
   }

   void PrintString() {
      String ^ targetStr = x;
      Console::WriteLine("StringWrapper::x == {0}", targetStr);
   }
};
#pragma unmanaged
int main() {
   StringWrapper s;
   s.PrintString();
}
StringWrapper::x == ManagedString

GCHandle 에서는 관리되는 개체 참조를 관리되지 않는 메모리에 보관할 수 있는 방법을 제공합니다. 이 메서드를 Alloc 사용하여 관리되는 개체 Free 에 대한 불투명 핸들을 만들고 해제합니다. 또한 이 Target 메서드를 사용하면 관리 코드의 핸들에서 개체 참조를 다시 가져올 수 있습니다.

// hold_object_reference_2.cpp
// compile with: /clr
using namespace System;
using namespace System::Runtime::InteropServices;

#pragma managed
class StringWrapper {
   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();
   }

   void PrintString() {
      String ^ targetStr = safe_cast< String ^ >(static_cast<GCHandle>(m_handle).Target);
      Console::WriteLine("StringWrapper::m_handle == {0}", targetStr);
   }
};

#pragma unmanaged
int main() {
   StringWrapper s;
   s.PrintString();
}
StringWrapper::m_handle == ManagedString

참고 항목

C++ Interop 사용(암시적 PInvoke)