C#
public override int Read (byte[] buffer, int offset, int count);
Parameters
-
buffer
- Byte[]
当此方法返回时,包含指定的字节数组,此数组中 offset
和 (offset
+ count
- 1) 之间的值被从当前源中读取的字节所替换。 此参数在传递时尚未初始化。
-
offset
- Int32
buffer
中的从零开始的字节偏移量,从此处开始存储从当前流中读取的数据。
-
count
- Int32
要从当前流中读取的最大字节数。
Returns
- Int32
读入缓冲区中的总字节数。 如果许多字节当前不可用,则该数字可能小于要求的字节数;如果尚未到达流的末尾,则为零 (0)。
Exceptions
基础内存不支持读取。
- 或 -
CanRead 属性设置为 false
。
offset
参数小于零。
- 或 -
count
参数小于零。
缓冲区数组的长度减去 offset
参数小于 count
参数。
Examples
下面的代码示例演示如何使用 UnmanagedMemoryStream 类读取和写入非托管内存。 使用 Marshal 类分配并取消分配非托管内存块。
C#
// Note: you must compile this sample using the unsafe flag.
// From the command line, type the following: csc sample.cs /unsafe
using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
unsafe class TestWriter
{
static void Main()
{
// Create some data to read and write.
byte[] message = UnicodeEncoding.Unicode.GetBytes("Here is some data.");
// Allocate a block of unmanaged memory and return an IntPtr object.
IntPtr memIntPtr = Marshal.AllocHGlobal(message.Length);
// Get a byte pointer from the IntPtr object.
byte* memBytePtr = (byte*)memIntPtr.ToPointer();
// Create an UnmanagedMemoryStream object using a pointer to unmanaged memory.
UnmanagedMemoryStream writeStream = new UnmanagedMemoryStream(memBytePtr, message.Length, message.Length, FileAccess.Write);
// Write the data.
writeStream.Write(message, 0, message.Length);
// Close the stream.
writeStream.Close();
// Create another UnmanagedMemoryStream object using a pointer to unmanaged memory.
UnmanagedMemoryStream readStream = new UnmanagedMemoryStream(memBytePtr, message.Length, message.Length, FileAccess.Read);
// Create a byte array to hold data from unmanaged memory.
byte[] outMessage = new byte[message.Length];
// Read from unmanaged memory to the byte array.
readStream.Read(outMessage, 0, message.Length);
// Close the stream.
readStream.Close();
// Display the data to the console.
Console.WriteLine(UnicodeEncoding.Unicode.GetString(outMessage));
// Free the block of unmanaged memory.
Marshal.FreeHGlobal(memIntPtr);
Console.ReadLine();
}
}
Remarks
offset
参数提供 array
参数(缓冲区索引)中的字节偏移量,从此处开始读取,count
参数提供要从此流中读取的最大字节数。 返回的值是读取的实际字节数,或者如果到达流的末尾,则为零。 如果读取操作成功,则流的当前位置将按读取的字节数提前。 如果发生异常,则流的当前位置不变。
仅在到达流的末尾后,Read 方法返回零。 否则,Read 始终从流中读取至少一个字节,然后返回。 如果在调用 Read时流中没有可用数据,则该方法将一直阻止到至少有一个字节的数据返回。 即使尚未到达流的末尾,实现也可以自由返回比请求更少的字节。