int*、char**、int(*)[3]。int* 指向 int。&a:取地址,產生指向 a 類型的指針。*p:間接訪問,結果類型為 p 指向類型,地址為 p 的值。new/delete 操作堆內存。C# 預設不允許指針,需在專案屬性勾選「允許不安全代碼」,並在方法/類前加 unsafe。
fixed 關鍵字「釘住」托管對象,防止 GC 移動內存導致指針失效。
public static unsafe void Copy(byte[] src, int srcIdx,
byte[] dst, int dstIdx, int count) {
fixed (byte* pSrc = src, pDst = dst) {
byte* ps = pSrc + srcIdx;
byte* pd = pDst + dstIdx;
for (int i = 0; i < count / 4; ++i) {
*((int*)pd) = *((int*)ps);
pd += 4; ps += 4;
}
for (int i = 0; i < count % 4; ++i) *pd++ = *ps++;
}
}