1. Cases where a managed class member variable is included in a local class
1#include <vcclr.h>//must contain vcclr.h header file2 3 //Incoming4 5a^ A =gcnew A ();6 7Gcroot<a^> *pa =NewGcroot<a^>();8 9*PA =A;Ten One void*ptr =PA; A -B *b =NewB (PA);//C + + class - the //Restore - -gcroot<a^> * M_pa = (gcroot<a^> *) PA; - +(*M_PA)->funca ();//can call Class A interface;
2.PIN_PTR is an internal pointer that prevents your object from moving in the garbage collection heap. This means that the value of the pinning pointer is not changed by the common language runtime. This is useful when passing the address of a managed class to an unmanaged function, because the address does not change unexpectedly during the parsing of an unmanaged function call.
Pin_ptr not available (valid for pin_ptr life cycle):
-
function parameters
As the return type of the function.
Declaration of a class member
The type constraint for the target.
Pin_ptr the position of the first element of the array
1 //Pin_ptr_1.cpp2 //compile with:/clr3 using namespaceSystem; 4 #defineSIZE 105 6 #pragmaUnmanaged7 //Native function that initializes an array8 voidNative_function (int*p) {9 for(inti =0; I <Ten; i++) TenP[i] =i; One } A #pragmaManaged - - Public ref classA { the Private: -array<int>^ arr;//CLR Integer Array - - Public: + A () { -arr = gcnew array<int>(SIZE); + } A at voidload () { -pin_ptr<int> P = &arr[0];//pin pointer to first element in arr - int* NP = P;//Pointer to the first element in arr -Native_function (NP);//pass pointer to native function - } - in intsum () { - intTotal =0; to for(inti =0; i < SIZE; i++) +Total + =Arr[i]; - returnTotal ; the } * }; $ Panax Notoginseng intMain () { -a^ A =gcnew A; theA->load ();//Initialize managed array using the native function +Console::WriteLine (a->sum ()); A}
View Code
The internal pointer is converted to a pinned pointer, and the type returned by the address-of operator (&) is an internal pointer when the operand is in the managed heap
1 //Pin_ptr_2.cpp2 //compile with:/clr3 using namespaceSystem; 4 5 ref structG {6G (): I (1) {} 7 inti; 8 }; 9 Ten ref structH { OneH (): J (2) {} A intJ; - }; - the intMain () { -g ^ g = gcnew g;//G is a whole reference object pointer -H ^ h =gcnew H; - +interior_ptr<int> L = & (G->i);//L is interior pointer - +pin_ptr<int> k = & (H->J);//K is a pinning interior pointer A atK = l;//OK -Console::WriteLine (*k); -};
View Code
The pinned pointer is converted to another type
1 //Pin_ptr_3.cpp2 //compile with:/clr3 using namespaceSystem; 4 5 ref classManagedType {6 Public: 7 inti; 8 }; 9 Ten intMain () { OneManagedType ^MT =gcnew ManagedType; Apin_ptr<int> pt = &mt->i; -*PT =8; -Console::WriteLine (mt->i); the - Char*PC = (Char*) pt; -*PC =255; -Console::WriteLine (mt->i); +}
View Code
C + +/CLI Clips