Chapter 25 Quick Reference


Do this

Obtain a safe handle to a managed object so that it won’t be garbage collected while being used.

Use the System::Runtime::InteropServices::GCHandle::Alloc function to wrap a pointer to a managed object in a GCHandle. The easiest way to do this is to use the gcroot helper class. For example:

Foo* ff = new unmanaged code Foo(); gcroot<Foo*> pf = ff;

This code wraps the pointer to the Foo object with a GCHandle, and handles cleanup when the gcroot is destroyed.

Fix all or part of a managed object in memory so that it can safely be used by unmanaged code.

Use the __pin keyword to create a pinning pointer. For example:

Foo __pin * ptr = new Foo();

The managed Foo object won’t be moved in memory or garbage collected until the pinning pointer goes out of context or has 0 assigned to it.

Convert a value type to an object so that it can be used where an object is required.

Use the __box keyword to create an object wrapper. For example:

int n = 3; Object* po = __box(n);

Note that the value in the box is a copy of the original.

Retrieve the value from a boxed object.

Use dynamic_cast to cast the boxing object to the correct type, and then dereference the pointer. For example:

int myVal = *dynamic_cast<__box int*>(po);

Call an unmanaged function in a DLL.

Use the Platform Invoke mechanism by declaring a prototype for the unmanaged function that uses the DllImportAttribute class to specify the DLL in which the function lives and other optional parameters.

Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
Year: 2003
Pages: 208 © 2008-2017.
If you may any questions please contact us: