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

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

MemoryStream will take a byte[] but I'd like to do this without copying the data if possible.

Kirill Kobelev
  • 10,252
  • 6
  • 30
  • 51
Adam Tegen
  • 25,378
  • 33
  • 125
  • 153

2 Answers2

8

You can avoid the copy if you use an UnmanagedMemoryStream() instead (class exists in .NET FCL 2.0 and later). Like MemoryStream, it is a subclass of IO.Stream, and has all the usual stream operations.

Microsoft's description of the class is:

Provides access to unmanaged blocks of memory from managed code.

which pretty much tells you what you need to know. Note that UnmanagedMemoryStream() is not CLS-compliant.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
McKenzieG1
  • 13,960
  • 7
  • 36
  • 42
  • Note: this answer only works in unsafe code. If you do not compile with the unsafe flag, you may have better luck by Marshalling the data to a byte array, then wrapping that byte array in a stream. See here: http://stackoverflow.com/a/11660831/684852 You need to know the length of the data (number of bytes in the original unicode string at your pointer) though. For example: `byte[] dataArray = new byte[dataLength]; Marshal.Copy(szUnicodeString, dataArray, 0, dataLength); MemoryStream stream = new MemoryStream(dataArray);` – Sean Colombo Dec 22 '13 at 21:57
0

If I had to copy the memory, I think the following would work:


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);
}
Adam Tegen
  • 25,378
  • 33
  • 125
  • 153