Pergunta

class Foo
{
   static bool Bar(Stream^ stream);
};

class FooWrapper
{
   bool Bar(LPCWSTR szUnicodeString)
   {
       return Foo::Bar(??);
   }
};

MemoryStream vai levar um byte[] mas eu como fazer isso sem copiar os dados, se possível.

Foi útil?

Solução

Você pode evitar a cópia se usar um UnmanagedMemoryStream() em vez disso (a classe existe no .NET FCL 2.0 e posterior).Como MemoryStream, é uma subclasse de IO.Stream, e tem todas as operações usuais de stream.

A descrição da classe pela Microsoft é:

Fornece acesso a blocos de memória não gerenciados de código gerenciado.

que praticamente diz o que você precisa saber.Observe que UnmanagedMemoryStream() não é compatível com CLS.

Outras dicas

Se eu tivesse que copiar a memória, acho que o seguinte funcionaria:


static Stream^ UnicodeStringToStream(LPCWSTR szUnicodeString)
{
   //validate the input parameter
   if (szUnicodeString == NULL)
   {
      return nullptr;
   }

   //get the length of the string
   size_t lengthInWChars = wcslen(szUnicodeString);  
   size_t lengthInBytes = lengthInWChars * sizeof(wchar_t);

   //allocate the .Net byte array
   array^ byteArray = gcnew array(lengthInBytes);

   //copy the unmanaged memory into the byte array
   Marshal::Copy((IntPtr)(void*)szUnicodeString, byteArray, 0, lengthInBytes);

   //create a memory stream from the byte array
   return gcnew MemoryStream(byteArray);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top