C# 指標的使用 ref byte 轉 byte 或 byte [] ref 與指標
C# 不推薦用指標,但可以使用指標,同時在某些情況下又不得不使用指標,比如C#呼叫了C++的DLL,而經常會用到指標
下在介紹C#程式碼中使用指標:
1,首先要使用指標,先在要C#工程屬性中設定 ( 右鍵工程名 -》屬性-》生成 ) ”允許不安全程式碼“:
2,新增 引用 using System.IO;
3,工程中用到指標的針碼段用 unsafe{ } 包住,如下:
unsafe
{
fixed ( byte* p = &buf )
{
using (UnmanagedMemoryStream ms = new UnmanagedMemoryStream((byte*)p, size, size, FileAccess.Read))
{
ms.Read(tbuf, 0, tbuf.Length);
}
}
}
4,設定 UnmanagedMemoryStream 的讀寫許可權:FileAccess.Read ,FileAccess.Write ,FileAccess.ReadWrite 三種
如,從指標中讀取內容到 Byte [] tbuf陣列中。
using (UnmanagedMemoryStream ms = new UnmanagedMemoryStream((byte*)p, size, size, FileAccess.Read))
{
ms.Read(tbuf, 0, tbuf.Length);
}
往指標中讀寫入 Byte [] tbuf陣列中 內容。
using (UnmanagedMemoryStream ms = new UnmanagedMemoryStream((byte*)p, size, size, FileAccess.ReadWrite))
{
ms.Write(tbuf, 0, size);
}
5,給下完整的實現例子
public void write(ref Byte buf, Byte size) { Byte[] tbuf = new Byte[size]; unsafe { fixed ( byte* p = &buf ) { using (UnmanagedMemoryStream ms = new UnmanagedMemoryStream((byte*)p, size, size, FileAccess.Read)) { ms.Read(tbuf, 0, tbuf.Length); } } } serialPort1.Write(tbuf, 0, size); return; } public Byte read(ref Byte buf, Byte size, Byte mstimeout) { Byte[] tbuf = new Byte[10]; DateTime now = DateTime.Now; int s,rc; do { rc = serialPort1.Read(tbuf, 0, size); if (rc == size) { unsafe { fixed ( byte* p = &buf ) { using (UnmanagedMemoryStream ms = new UnmanagedMemoryStream((byte*)p, size, size, FileAccess.ReadWrite)) { ms.Write(tbuf, 0, size); } } } ServoTest.Text = string.Format("{0:X02} {1:X02} {2:X02} {3:X02} {4:X02} {5:X02} {6:X02} {7:X02} {8:X02} {9:X02} ", tbuf[0], tbuf[1], tbuf[2], tbuf[3],tbuf[4],tbuf[5],tbuf[6],tbuf[7],tbuf[8],tbuf[9]); return 0; } TimeSpan spand = DateTime.Now - now; s = spand.Milliseconds; }while (s < mstimeout); return 1; }