UnmanagedMemoryStream Construtores
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Inicializa uma nova instância da classe UnmanagedMemoryStream.
Sobrecargas
| Nome | Description |
|---|---|
| UnmanagedMemoryStream() |
Inicializa uma nova instância da classe UnmanagedMemoryStream. |
| UnmanagedMemoryStream(Byte*, Int64) |
Inicializa uma nova instância da UnmanagedMemoryStream classe usando o local e o comprimento de memória especificados. |
| UnmanagedMemoryStream(SafeBuffer, Int64, Int64) |
Inicializa uma nova instância da UnmanagedMemoryStream classe em um buffer seguro com um deslocamento e comprimento especificados. |
| UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess) |
Inicializa uma nova instância da UnmanagedMemoryStream classe usando o local especificado, o comprimento da memória, a quantidade total de memória e os valores de acesso ao arquivo. |
| UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess) |
Inicializa uma nova instância da UnmanagedMemoryStream classe em um buffer seguro com um deslocamento, comprimento e acesso a arquivos especificados. |
UnmanagedMemoryStream()
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
Inicializa uma nova instância da classe UnmanagedMemoryStream.
protected:
UnmanagedMemoryStream();
protected UnmanagedMemoryStream();
Protected Sub New ()
Exceções
O usuário não tem a permissão necessária.
Aplica-se a
UnmanagedMemoryStream(Byte*, Int64)
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
Importante
Esta API não está em conformidade com CLS.
Inicializa uma nova instância da UnmanagedMemoryStream classe usando o local e o comprimento de memória especificados.
public:
UnmanagedMemoryStream(System::Byte* pointer, long length);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public UnmanagedMemoryStream(byte* pointer, long length);
[System.CLSCompliant(false)]
public UnmanagedMemoryStream(byte* pointer, long length);
public UnmanagedMemoryStream(byte* pointer, long length);
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new System.IO.UnmanagedMemoryStream : nativeptr<byte> * int64 -> System.IO.UnmanagedMemoryStream
[<System.CLSCompliant(false)>]
new System.IO.UnmanagedMemoryStream : nativeptr<byte> * int64 -> System.IO.UnmanagedMemoryStream
new System.IO.UnmanagedMemoryStream : nativeptr<byte> * int64 -> System.IO.UnmanagedMemoryStream
Parâmetros
- pointer
- Byte*
Um ponteiro para um local de memória não gerenciado.
- length
- Int64
O comprimento da memória a ser usada.
- Atributos
Exceções
O usuário não tem a permissão necessária.
O pointer valor é null.
O length valor é menor que zero.
- ou -
O length é grande o suficiente para causar um estouro.
Exemplos
O exemplo de código a seguir demonstra como ler e gravar em memória não gerenciada usando a UnmanagedMemoryStream classe. Um bloco de memória não gerenciada é alocado e desalocado usando a Marshal classe.
// 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.Runtime.InteropServices;
using System.Text;
unsafe class Program
{
static void Main()
{
// Create some data to write.
byte[] text = UnicodeEncoding.Unicode.GetBytes("Data to write.");
// Allocate a block of unmanaged memory.
IntPtr memIntPtr = Marshal.AllocHGlobal(text.Length);
// Get a byte pointer from the unmanaged memory block.
byte* memBytePtr = (byte*)memIntPtr.ToPointer();
UnmanagedMemoryStream writeStream =
new UnmanagedMemoryStream(
memBytePtr, text.Length, text.Length, FileAccess.Write);
// Write the data.
WriteToStream(writeStream, text);
// Close the stream.
writeStream.Close();
// Create another UnmanagedMemoryStream for reading.
UnmanagedMemoryStream readStream =
new UnmanagedMemoryStream(memBytePtr, text.Length);
// Display the contents of the stream to the console.
PrintStream(readStream);
// Close the reading stream.
readStream.Close();
// Free up the unmanaged memory.
Marshal.FreeHGlobal(memIntPtr);
}
public static void WriteToStream(UnmanagedMemoryStream writeStream, byte[] text)
{
// Verify that the stream is writable:
// By default, UnmanagedMemoryStream objects do not have write access,
// write access must be set explicitly.
if (writeStream.CanWrite)
{
// Write the data, byte by byte
for (int i = 0; i < writeStream.Length; i++)
{
writeStream.WriteByte(text[i]);
}
}
}
public static void PrintStream(UnmanagedMemoryStream readStream)
{
byte[] text = new byte[readStream.Length];
// Verify that the stream is writable:
// By default, UnmanagedMemoryStream objects do not have write access,
// write access must be set explicitly.
if (readStream.CanRead)
{
// Write the data, byte by byte
for (int i = 0; i < readStream.Length; i++)
{
text[i] = (byte)readStream.ReadByte();
}
}
Console.WriteLine(UnicodeEncoding.Unicode.GetString(text));
}
}
Comentários
Esse construtor cria uma nova instância da UnmanagedMemoryStream classe e, por padrão, define a CanWrite propriedade false como e a CanRead propriedade como true. A Length propriedade é definida como o valor do length parâmetro e não pode ser alterada.
Aplica-se a
UnmanagedMemoryStream(SafeBuffer, Int64, Int64)
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
Inicializa uma nova instância da UnmanagedMemoryStream classe em um buffer seguro com um deslocamento e comprimento especificados.
public:
UnmanagedMemoryStream(System::Runtime::InteropServices::SafeBuffer ^ buffer, long offset, long length);
public UnmanagedMemoryStream(System.Runtime.InteropServices.SafeBuffer buffer, long offset, long length);
new System.IO.UnmanagedMemoryStream : System.Runtime.InteropServices.SafeBuffer * int64 * int64 -> System.IO.UnmanagedMemoryStream
Public Sub New (buffer As SafeBuffer, offset As Long, length As Long)
Parâmetros
- buffer
- SafeBuffer
O buffer para conter o fluxo de memória não gerenciado.
- offset
- Int64
A posição de byte no buffer no qual iniciar o fluxo de memória não gerenciado.
- length
- Int64
O comprimento do fluxo de memória não gerenciado.
Aplica-se a
UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess)
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
Importante
Esta API não está em conformidade com CLS.
Inicializa uma nova instância da UnmanagedMemoryStream classe usando o local especificado, o comprimento da memória, a quantidade total de memória e os valores de acesso ao arquivo.
public:
UnmanagedMemoryStream(System::Byte* pointer, long length, long capacity, System::IO::FileAccess access);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public UnmanagedMemoryStream(byte* pointer, long length, long capacity, System.IO.FileAccess access);
[System.CLSCompliant(false)]
public UnmanagedMemoryStream(byte* pointer, long length, long capacity, System.IO.FileAccess access);
public UnmanagedMemoryStream(byte* pointer, long length, long capacity, System.IO.FileAccess access);
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new System.IO.UnmanagedMemoryStream : nativeptr<byte> * int64 * int64 * System.IO.FileAccess -> System.IO.UnmanagedMemoryStream
[<System.CLSCompliant(false)>]
new System.IO.UnmanagedMemoryStream : nativeptr<byte> * int64 * int64 * System.IO.FileAccess -> System.IO.UnmanagedMemoryStream
new System.IO.UnmanagedMemoryStream : nativeptr<byte> * int64 * int64 * System.IO.FileAccess -> System.IO.UnmanagedMemoryStream
Parâmetros
- pointer
- Byte*
Um ponteiro para um local de memória não gerenciado.
- length
- Int64
O comprimento da memória a ser usada.
- capacity
- Int64
A quantidade total de memória atribuída ao fluxo.
- access
- FileAccess
Um dos FileAccess valores.
- Atributos
Exceções
O usuário não tem a permissão necessária.
O pointer valor é null.
O length valor é menor que zero.
- ou -
O capacity valor é menor que zero.
- ou -
O length valor é maior que o capacity valor.
Exemplos
O exemplo de código a seguir demonstra como ler e gravar em memória não gerenciada usando a UnmanagedMemoryStream classe. Um bloco de memória não gerenciada é alocado e desalocado usando a Marshal classe.
// 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
O length parâmetro define a quantidade atual de memória em uso. Se estiver lendo ou acrescentando dados ao fluxo, o length valor deverá ser igual à quantidade de dados válidos no fluxo a ser lido ou preservado. Se estiver gravando no fluxo, esse valor deverá ser zero.
O capacity parâmetro indica a quantidade de memória total disponível. Esse valor pode descrever uma região maior que o comprimento especificado ou indicar uma região à qual pode ser acrescentado. Qualquer tentativa de gravar além desse valor falhará.
O access parâmetro define as propriedades e CanWrite o CanReadparâmetro. Observe que especificar Write não garante que o fluxo será gravável. Os parâmetros de acesso permitem que o implementador crie um objeto cuja implementação possa corresponder ao fluxo real exposto.
Aplica-se a
UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess)
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
- Origem:
- UnmanagedMemoryStream.cs
Inicializa uma nova instância da UnmanagedMemoryStream classe em um buffer seguro com um deslocamento, comprimento e acesso a arquivos especificados.
public:
UnmanagedMemoryStream(System::Runtime::InteropServices::SafeBuffer ^ buffer, long offset, long length, System::IO::FileAccess access);
public UnmanagedMemoryStream(System.Runtime.InteropServices.SafeBuffer buffer, long offset, long length, System.IO.FileAccess access);
new System.IO.UnmanagedMemoryStream : System.Runtime.InteropServices.SafeBuffer * int64 * int64 * System.IO.FileAccess -> System.IO.UnmanagedMemoryStream
Public Sub New (buffer As SafeBuffer, offset As Long, length As Long, access As FileAccess)
Parâmetros
- buffer
- SafeBuffer
O buffer para conter o fluxo de memória não gerenciado.
- offset
- Int64
A posição de byte no buffer no qual iniciar o fluxo de memória não gerenciado.
- length
- Int64
O comprimento do fluxo de memória não gerenciado.
- access
- FileAccess
O modo de acesso de arquivo ao fluxo de memória não gerenciado.