Nicholas
Nicholas

Reputation: 1462

Boxing Native C++ Pointer

I have a pointer to a native class and want to temporarily wrap it in a Object. I assume the System::Reflection::Pointer::Box() function would be the way to go. However I'm having trouble formatting the second parameter to it.

class A {}
A * a;
Object ^ o = Box(a, A::typeid);

I get a runtime error that says 'Type must be a pointer', as I suppose it should be. But I cannot figure out the syntax.

Upvotes: 0

Views: 847

Answers (1)

mcdave
mcdave

Reputation: 2580

I couldn't get System.Reflection.Pointer.Box to work either, but found the capability to do what you are trying with humble IntPtr.

A * a = new A;
Object ^o = gcnew IntPtr(a); // a is boxed in o
IntPtr i = safe_cast<IntPtr>(o); // Unbox the IntPtr
A * aIsBack = static_cast<A*>(i.ToPointer()); // Retrieve a

Upvotes: 1

Related Questions