UnmanagedMemoryStream Classe
Definição
Importante
Esta API não está em conformidade com CLS.
Fornece acesso aos blocos de memória não gerenciados a partir de código gerenciado.Provides access to unmanaged blocks of memory from managed code.
public ref class UnmanagedMemoryStream : System::IO::Stream
public class UnmanagedMemoryStream : System.IO.Stream
[System.CLSCompliant(false)]
public class UnmanagedMemoryStream : System.IO.Stream
type UnmanagedMemoryStream = class
inherit Stream
[<System.CLSCompliant(false)>]
type UnmanagedMemoryStream = class
inherit Stream
Public Class UnmanagedMemoryStream
Inherits Stream
- Herança
- Herança
- Derivado
- Atributos
Exemplos
O exemplo de código a seguir demonstra como ler e gravar na memória não gerenciada usando a UnmanagedMemoryStream classe.The following code example demonstrates how to read from and write to unmanaged memory using the UnmanagedMemoryStream class. Um bloco de memória não gerenciada é alocado e desalocado usando a Marshal classe.A block of unmanaged memory is allocated and de-allocated using the Marshal class.
// 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();
}
}
Comentários
Essa classe dá suporte ao acesso à memória não gerenciada usando o modelo existente baseado em fluxo e não requer que o conteúdo na memória não gerenciada seja copiado para o heap.This class supports access to unmanaged memory using the existing stream-based model and does not require that the contents in the unmanaged memory be copied to the heap.
Observação
Esse tipo implementa a interface IDisposable, mas, na verdade, não tem todos os recursos para descarte.This type implements the IDisposable interface, but does not actually have any resources to dispose. Isso significa que não é necessário descartá-lo chamando diretamente Dispose() ou usando um constructo de linguagem como using (em C#) ou Using (em Visual Basic).This means that disposing it by directly calling Dispose() or by using a language construct such as using (in C#) or Using (in Visual Basic) is not necessary.
Construtores
| UnmanagedMemoryStream() |
Inicializa uma nova instância da classe UnmanagedMemoryStream.Initializes a new instance of the UnmanagedMemoryStream class. |
| UnmanagedMemoryStream(Byte*, Int64) |
Inicializa uma nova instância da classe UnmanagedMemoryStream usando o tamanho da memória e o local especificados.Initializes a new instance of the UnmanagedMemoryStream class using the specified location and memory length. |
| UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess) |
Inicializa uma nova instância da classe UnmanagedMemoryStream usando o local, o tamanho da memória, a quantidade total de memória e os valores de acesso ao arquivo.Initializes a new instance of the UnmanagedMemoryStream class using the specified location, memory length, total amount of memory, and file access values. |
| UnmanagedMemoryStream(SafeBuffer, Int64, Int64) |
Inicializa uma nova instância da classe UnmanagedMemoryStream em um buffer seguro com deslocamento e comprimento especificados.Initializes a new instance of the UnmanagedMemoryStream class in a safe buffer with a specified offset and length. |
| UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess) |
Inicializa uma nova instância da classe UnmanagedMemoryStream em um buffer seguro com um deslocamento, tamanho e acesso a arquivos especificados.Initializes a new instance of the UnmanagedMemoryStream class in a safe buffer with a specified offset, length, and file access. |
Propriedades
| CanRead |
Obtém um valor que indica se um fluxo oferece suporte à leitura.Gets a value indicating whether a stream supports reading. |
| CanSeek |
Obtém um valor que indica se um fluxo oferece suporte à busca.Gets a value indicating whether a stream supports seeking. |
| CanTimeout |
Obtém um valor que determina se o fluxo atual pode atingir o tempo limite.Gets a value that determines whether the current stream can time out. (Herdado de Stream) |
| CanWrite |
Obtém um valor que indica se um fluxo oferece suporte à gravação.Gets a value indicating whether a stream supports writing. |
| Capacity |
Obtém o comprimento do fluxo (tamanho) ou a quantidade total de memória atribuída a um fluxo (capacidade).Gets the stream length (size) or the total amount of memory assigned to a stream (capacity). |
| Length |
Obtém o comprimento dos dados em um fluxo.Gets the length of the data in a stream. |
| Position |
Obtém ou define a posição atual em um fluxo.Gets or sets the current position in a stream. |
| PositionPointer |
Obtém ou define um ponteiro de bytes em um fluxo com base na posição atual no fluxo.Gets or sets a byte pointer to a stream based on the current position in the stream. |
| ReadTimeout |
Obtém ou define um valor, em milissegundos, que determina por quanto tempo o fluxo tentará realizar a leitura antes do tempo limite.Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out. (Herdado de Stream) |
| WriteTimeout |
Obtém ou define um valor, em milissegundos, que determina por quanto tempo o fluxo tentará realizar a gravação antes do tempo limite.Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out. (Herdado de Stream) |
Métodos
| BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) |
Inicia uma operação de leitura assíncrona.Begins an asynchronous read operation. (Considere o uso de ReadAsync(Byte[], Int32, Int32) em seu lugar.)(Consider using ReadAsync(Byte[], Int32, Int32) instead.) (Herdado de Stream) |
| BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) |
Inicia uma operação de gravação assíncrona.Begins an asynchronous write operation. (Considere o uso de WriteAsync(Byte[], Int32, Int32) em seu lugar.)(Consider using WriteAsync(Byte[], Int32, Int32) instead.) (Herdado de Stream) |
| Close() |
Fecha o fluxo atual e libera todos os recursos (como soquetes e identificadores de arquivos) associados ao fluxo atual.Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Em vez de chamar esse método, verifique se o fluxo é descartado corretamente.Instead of calling this method, ensure that the stream is properly disposed. (Herdado de Stream) |
| CopyTo(Stream) |
Lê os bytes do fluxo atual e os grava em outro fluxo.Reads the bytes from the current stream and writes them to another stream. (Herdado de Stream) |
| CopyTo(Stream, Int32) |
Lê os bytes do fluxo atual e os grava em outro fluxo usando um tamanho do buffer especificado.Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. (Herdado de Stream) |
| CopyToAsync(Stream) |
Lê de forma assíncrona os bytes do fluxo atual e os grava em outro fluxo.Asynchronously reads the bytes from the current stream and writes them to another stream. (Herdado de Stream) |
| CopyToAsync(Stream, CancellationToken) |
Lê de forma assíncrona os bytes do fluxo atual e os grava em outro fluxo usando um token de cancelamento especificado.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token. (Herdado de Stream) |
| CopyToAsync(Stream, Int32) |
Lê de maneira assíncrona os bytes do fluxo atual e os grava em outro fluxo usando um tamanho do buffer especificado.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size. (Herdado de Stream) |
| CopyToAsync(Stream, Int32, CancellationToken) |
Lê de forma assíncrona os bytes do fluxo atual e os grava em outro fluxo usando um tamanho do buffer especificado e um token de cancelamento.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token. (Herdado de Stream) |
| CreateObjRef(Type) |
Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Herdado de MarshalByRefObject) |
| CreateWaitHandle() |
Obsoleto.
Aloca um objeto WaitHandle.Allocates a WaitHandle object. (Herdado de Stream) |
| Dispose() |
Libera todos os recursos usados pelo Stream.Releases all resources used by the Stream. (Herdado de Stream) |
| Dispose(Boolean) |
Libera os recursos não gerenciados usados pelo UnmanagedMemoryStream e opcionalmente libera os recursos gerenciados.Releases the unmanaged resources used by the UnmanagedMemoryStream and optionally releases the managed resources. |
| DisposeAsync() |
Libera de forma assíncrona os recursos não gerenciados usados pelo Stream.Asynchronously releases the unmanaged resources used by the Stream. (Herdado de Stream) |
| EndRead(IAsyncResult) |
Espera a leitura assíncrona pendente ser concluída.Waits for the pending asynchronous read to complete. (Considere o uso de ReadAsync(Byte[], Int32, Int32) em seu lugar.)(Consider using ReadAsync(Byte[], Int32, Int32) instead.) (Herdado de Stream) |
| EndWrite(IAsyncResult) |
Encerra uma operação de gravação assíncrona.Ends an asynchronous write operation. (Considere o uso de WriteAsync(Byte[], Int32, Int32) em seu lugar.)(Consider using WriteAsync(Byte[], Int32, Int32) instead.) (Herdado de Stream) |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| Flush() |
Substitui o método Flush() para que nenhuma ação seja executada.Overrides the Flush() method so that no action is performed. |
| FlushAsync() |
Limpa de forma assíncrona todos os buffers nesse fluxo e faz com que os dados armazenados em buffer sejam gravados no dispositivo subjacente.Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device. (Herdado de Stream) |
| FlushAsync(CancellationToken) |
Substitui o método FlushAsync(CancellationToken) para que a operação seja cancelada se especificado, mas nenhuma outra ação seja executada.Overrides the FlushAsync(CancellationToken) method so that the operation is cancelled if specified, but no other action is performed. |
| FlushAsync(CancellationToken) |
Limpa todos os buffers nesse fluxo de forma assíncrona, faz com que os dados armazenados em buffer sejam gravados no dispositivo subjacente e monitora as solicitações de cancelamento.Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests. (Herdado de Stream) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetLifetimeService() |
Obsoleto.
Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Herdado de MarshalByRefObject) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| Initialize(Byte*, Int64, Int64, FileAccess) |
Inicializa uma nova instância da classe UnmanagedMemoryStream usando um ponteiro para um local de memória não gerenciada.Initializes a new instance of the UnmanagedMemoryStream class by using a pointer to an unmanaged memory location. |
| Initialize(SafeBuffer, Int64, Int64, FileAccess) |
Inicializa uma nova instância da classe UnmanagedMemoryStream em um buffer seguro com um deslocamento, tamanho e acesso a arquivos especificados.Initializes a new instance of the UnmanagedMemoryStream class in a safe buffer with a specified offset, length, and file access. |
| InitializeLifetimeService() |
Obsoleto.
Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.Obtains a lifetime service object to control the lifetime policy for this instance. (Herdado de MarshalByRefObject) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| MemberwiseClone(Boolean) |
Cria uma cópia superficial do objeto MarshalByRefObject atual.Creates a shallow copy of the current MarshalByRefObject object. (Herdado de MarshalByRefObject) |
| ObjectInvariant() |
Obsoleto.
Oferece suporte a um Contract.Provides support for a Contract. (Herdado de Stream) |
| Read(Byte[], Int32, Int32) |
Lê o número de bytes especificado na matriz especificada.Reads the specified number of bytes into the specified array. |
| Read(Span<Byte>) |
Lê todos os bytes desse fluxo de memória não gerenciado no intervalo especificado de bytes.Reads all the bytes of this unmanaged memory stream into the specified span of bytes. |
| Read(Span<Byte>) |
Quando for substituído em uma classe derivada, lê uma sequência de bytes do fluxo atual e avança a posição dentro do fluxo até o número de bytes lidos.When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. (Herdado de Stream) |
| ReadAsync(Byte[], Int32, Int32) |
Lê uma sequência de bytes do fluxo atual de forma assíncrona e avança a posição no fluxo até o número de bytes lidos.Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. (Herdado de Stream) |
| ReadAsync(Byte[], Int32, Int32, CancellationToken) |
Lê de forma assíncrona o número de bytes especificado na matriz especificada.Asynchronously reads the specified number of bytes into the specified array. |
| ReadAsync(Byte[], Int32, Int32, CancellationToken) |
Lê de forma assíncrona uma sequência de bytes do fluxo atual, avança a posição no fluxo até o número de bytes lidos e monitora as solicitações de cancelamento.Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. (Herdado de Stream) |
| ReadAsync(Memory<Byte>, CancellationToken) |
Lê de forma assíncrona os bytes de fluxo de memória não gerenciado na região de memória.Asynchronously reads the unmanaged memory stream bytes into the memory region. |
| ReadAsync(Memory<Byte>, CancellationToken) |
Lê de forma assíncrona uma sequência de bytes do fluxo atual, avança a posição no fluxo até o número de bytes lidos e monitora as solicitações de cancelamento.Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. (Herdado de Stream) |
| ReadByte() |
Lê um byte de um fluxo e avança a posição no fluxo em um byte ou retorna -1 caso esteja no final do fluxo.Reads a byte from a stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. |
| Seek(Int64, SeekOrigin) |
Define a posição atual do fluxo atual como o valor determinado.Sets the current position of the current stream to the given value. |
| SetLength(Int64) |
Define o comprimento de um fluxo como um valor especificado.Sets the length of a stream to a specified value. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
| Write(Byte[], Int32, Int32) |
Grava um bloco de bytes no fluxo atual usando os dados de um buffer.Writes a block of bytes to the current stream using data from a buffer. |
| Write(ReadOnlySpan<Byte>) |
Grava um bloco de bytes no fluxo de memória não gerenciado atual usando dados do intervalo de bytes fornecido.Writes a block of bytes to the current unmanaged memory stream using data from the provided span of bytes. |
| Write(ReadOnlySpan<Byte>) |
Quando for substituído em uma classe derivada, grava uma sequência de bytes no fluxo atual e avança a posição atual dentro desse fluxo até o número de bytes gravados.When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. (Herdado de Stream) |
| WriteAsync(Byte[], Int32, Int32) |
Grava assincronamente uma sequência de bytes no fluxo atual e avança a posição atual dentro desse fluxo no número de bytes gravados.Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. (Herdado de Stream) |
| WriteAsync(Byte[], Int32, Int32, CancellationToken) |
Grava uma sequência de bytes no fluxo atual assincronamente, avança a posição atual dentro desse fluxo pelo número de bytes gravados e monitora as solicitações de cancelamento.Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. |
| WriteAsync(Byte[], Int32, Int32, CancellationToken) |
Grava uma sequência de bytes no fluxo atual assincronamente, avança a posição atual dentro desse fluxo pelo número de bytes gravados e monitora as solicitações de cancelamento.Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. (Herdado de Stream) |
| WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) |
Grava de forma assíncrona um intervalo de bytes no fluxo atual, avança a posição atual nesse fluxo até o número de bytes gravados e monitora as solicitações de cancelamento.Asynchronously writes a span of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. |
| WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) |
Grava uma sequência de bytes no fluxo atual assincronamente, avança a posição atual dentro desse fluxo pelo número de bytes gravados e monitora as solicitações de cancelamento.Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. (Herdado de Stream) |
| WriteByte(Byte) |
Grava um byte na posição atual no fluxo de arquivos.Writes a byte to the current position in the file stream. |
Implantações explícitas de interface
| IDisposable.Dispose() |
Libera todos os recursos usados pelo Stream.Releases all resources used by the Stream. (Herdado de Stream) |
Métodos de Extensão
| AsInputStream(Stream) |
Converte um fluxo gerenciado no .NET para Aplicativos da Windows Store em um fluxo de entrada no Windows Runtime.Converts a managed stream in the .NET for Windows Store apps to an input stream in the Windows Runtime. |
| AsOutputStream(Stream) |
Converte um fluxo gerenciado no .NET para Aplicativos da Windows Store em um fluxo de saída no Windows Runtime.Converts a managed stream in the .NET for Windows Store apps to an output stream in the Windows Runtime. |
| AsRandomAccessStream(Stream) |
Converte o fluxo especificado em um fluxo de acesso aleatório.Converts the specified stream to a random access stream. |
| ConfigureAwait(IAsyncDisposable, Boolean) |
Configura como as esperas nas tarefas retornadas de um descartável assíncrono são realizadas.Configures how awaits on the tasks returned from an async disposable are performed. |