pin_cast.h
#pragma once
#include <vcclr.h>
using namespace System::Runtime::InteropServices;
template <class T>
struct pin_cast
{
private:
intptr_t _handle;
T* operator& ();
// hidden zero-param construct
pin_cast();
public:
pin_cast(Object* o)
{
_handle = GCHandle::op_Explicit
(GCHandle::Alloc(o, GCHandleType::Pinned))
#ifdef _WIN32
.ToInt32()
#elif defined(_WIN64)
.ToInt64()
#else
#error ERROR: either _WIN64 or _WIN32 must be defined
#endif
;
}
~pin_cast()
{
System::Runtime::InteropServices::GCHandle::op_Explicit
(_handle).Free();
_handle = 0;
}
operator T () const
{
return reinterpret_cast<const T>
(System::Runtime::InteropServices::GCHandle::op_Explicit(_handle)
.AddrOfPinnedObject().ToInt32());
}
};
End of Listing