Condividi tramite


Procedura: mantenere i riferimenti agli oggetti nella memoria non gestita

È possibile usare gcroot.h, che esegue il wrapping GCHandledi , per contenere un riferimento a un oggetto CLR nella memoria non gestita. In alternativa, è possibile usare GCHandle direttamente.

Esempi

// 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 consente di contenere un riferimento a un oggetto gestito nella memoria non gestita. Usare il Alloc metodo per creare un handle opaco in un oggetto gestito e Free rilasciarlo. Inoltre, il Target metodo consente di ottenere il riferimento all'oggetto dall'handle nel codice gestito.

// 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

Vedi anche

Uso delle funzionalità di interoperabilità C++ (PInvoke implicito)