Visual C++ .NET/Data Type/Pointer
Содержание
Address Indirect
#include "stdafx.h"
#using <mscorlib.dll>
using namespace System;
Int32 main(void)
{
Int32 x;
Int32 *y;
y = &x;
*y = 50;
Console::WriteLine(x);
return 0;
}
Int pointer
#include "stdafx.h"
using namespace System;
value class Test
{
public:
int i;
};
#pragma unmanaged
void incr (int *i)
{
(*i) += 10;
}
#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 );
}
Int Pointer Arithematic
#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);
}
Int Pointer with gcnew
#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);
}
Pointer To String Chars
#include "stdafx.h"
#include <msclr\all.h>
using namespace System;
void main()
{
String ^hstr = "Hello World!";
pin_ptr<const wchar_t> pstr = PtrToStringChars(hstr);
wprintf(pstr);
}
Using pointer arithmetic on the interior pointer
#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
}
}