次の方法で共有


方法: アンマネージ メモリ内にオブジェクト参照を保持する

GCHandle をラップする gcroot.h を使用して、アンマネージ メモリ内に 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();
}
  

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();
}
  

参照

関連項目

C++ Interop (暗黙の PInvoke) の使用