logo search
CSharp_Prog_Guide

Сравнение указателей

Для сравнения указателей любого типа можно использовать следующие операторы:

==   !=   <   >   <=   >=

Операторы сравнения сравнивают адреса двух операндов, как если бы они были беззнаковыми целыми числами.

Пример

-------

Пример результатов выполнения46

True

False

How to: Use Pointers to Copy an Array of Bytes

The following example uses pointers to copy bytes from one array to another using pointers.

This example uses the unsafe keyword, which allows pointers to be used within the Copy method. The fixed statement is used to declare pointers to the source and destination arrays. This pins the location of the source and destination arrays in memory so that they will not be moved by garbage collection. These memory blocks will be unpinned when the fixed block completes. Because the Copy function in this example uses the unsafe keyword, it must be compiled with /unsafe compiler option.

Example

// compile with: /unsafe

class TestCopy

{

// The unsafe keyword allows pointers to be used within the following method:

static unsafe void Copy(byte[] src, int srcIndex, byte[] dst, int dstIndex, int count)

{

if (src == null || srcIndex < 0 ||

dst == null || dstIndex < 0 || count < 0)

{

throw new System.ArgumentException();

}

int srcLen = src.Length;

int dstLen = dst.Length;

if (srcLen - srcIndex < count || dstLen - dstIndex < count)

{

throw new System.ArgumentException();

}

// The following fixed statement pins the location of the src and dst objects

// in memory so that they will not be moved by garbage collection.

fixed (byte* pSrc = src, pDst = dst)

{

byte* ps = pSrc;

byte* pd = pDst;

// Loop over the count in blocks of 4 bytes, copying an integer (4 bytes) at a time:

for (int i = 0 ; i < count / 4 ; i++)

{

*((int*)pd) = *((int*)ps);

pd += 4;

ps += 4;

}

// Complete the copy by moving any bytes that weren't moved in blocks of 4:

for (int i = 0; i < count % 4 ; i++)

{

*pd = *ps;

pd++;

ps++;

}

}

}