Pinning Managed Code

The code in Listing 1.4.3 would have a problem if you wanted to pass a pointer to an integer owned by a managed type. You will remember that managed objects can be moved around in memory by the Garbage Collector's compacting system, so pointers passed to unmanaged code must be guaranteed not to move. This is accomplished by pinning the object in place with the __pin keyword.

Listing 1.4.4 illustrates how a managed code object can be pinned to allow a pointer to be used.

Listing 1.4.4. pinned.cpp: Fixing Pointers by Pinning
#using <mscorlib.dll>
using namespace System;

#include "stdio.h"

__gc struct ManagedStruct
{
    int p;
    int q;
}; #pragma unmanaged void timestwo(int* pToMultiply) { *pToMultiply *= 2; } #pragma managed void ...

Get C# and the .NET Framework: The C++ Perspective now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.