Pinning Managed Code

I l @ ve RuBoard

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 main() {     ManagedStruct* pStruct=new ManagedStruct;     pStruct->p=1;     pStruct->q=2;     int __pin* pinnedp=&pStruct->p;     int __pin* pinnedq=&pStruct->q;     timestwo(pinnedp);     timestwo(pinnedq);     printf("p=%d, q=%d\ n",pStruct->p, pStruct->q); } 
I l @ ve RuBoard


C# and the .NET Framework. The C++ Perspective
C# and the .NET Framework
ISBN: 067232153X
EAN: 2147483647
Year: 2001
Pages: 204

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net