Visual C++ .NET/Data Type/Pointer

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Address Indirect

<source lang="csharp">

  1. include "stdafx.h"
  2. using <mscorlib.dll>

using namespace System; Int32 main(void) {

   Int32 x;   
   Int32 *y;  
   
   y = &x;     
   *y = 50;   
   Console::WriteLine(x);  
   return 0;

}

 </source>


Int pointer

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; value class Test { public:

   int i; 

};

  1. pragma unmanaged

void incr (int *i) {

   (*i) += 10;

}

  1. pragma managed

void main () {

   Test ^test = gcnew Test();
   interior_ptr<int> ip = &test->i;
   (*ip) = 5;
   pin_ptr<int> i = ip;  
   incr( i );             
                               
   Console::WriteLine ( test->i );

}

 </source>


Int Pointer Arithematic

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; void main() {

   array<int>^ primes = gcnew array<int> {1,2,3,5,7,11,13,17};
   interior_ptr<int> ip = &primes[0];       
   int total = 0;
   while(ip != &primes[0] + primes->Length) 
   {
       total += *ip;
       ip++;                                
   }
   Console::WriteLine(total);

}

 </source>


Int Pointer with gcnew

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; ref class Point { public:

   int X;

}; void main() {

   Point ^p = gcnew Point();
   interior_ptr<Point^> ip1 = &p;   // pointer to Point
   (*ip1)->X = 1;
   Console::WriteLine((int)&ip1);
   Console::WriteLine(p->X);
   Console::WriteLine((*ip1)->X);
   interior_ptr<int> ip2 = &p->X;  // pointer to Member variable X
   *ip2 += (*ip1)->X;
   Console::WriteLine((int)&ip2);
   Console::WriteLine(*ip2);

}

 </source>


Pointer To String Chars

<source lang="csharp">

  1. include "stdafx.h"
  2. include <msclr\all.h>

using namespace System; void main() {

   String ^hstr = "Hello World!";
   pin_ptr<const wchar_t> pstr = PtrToStringChars(hstr);
   wprintf(pstr);

}

 </source>


Using pointer arithmetic on the interior pointer

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; ref class MyObject { }; int main() {

  array<MyObject^>^ array_of_buf = gcnew array<MyObject^>(10);
  for each (MyObject^ bref in array_of_buf)
  {
     bref = gcnew MyObject();
  }
  interior_ptr<MyObject^> ptr_buf;
  for (ptr_buf = &array_of_buf[0]; ptr_buf <= &array_of_buf[9]; ptr_buf++)
  {
     MyObject^ buf = *ptr_buf;
     // use the MyObject class
  }

}

 </source>