如何将IntPtr转换为流?

时间:2020-03-05 18:47:15  来源:igfitidea点击:
class Foo
{
   static bool Bar(Stream^ stream);
};

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

" MemoryStream"将占用一个" byte []",但我希望在不复制数据的情况下做到这一点。

解决方案

回答

如果必须复制内存,我认为可以使用以下方法:

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);
}

回答

如果改用UnmanagedMemoryStream()(.NET FCL 2.0和更高版本中存在类),则可以避免复制。与MemoryStream一样,它是IO.Stream的子类,并具有所有常规的流操作。

微软对此类的描述是:

Provides access to unmanaged blocks of memory from managed code.

几乎可以告诉我们我们需要了解的内容。请注意," UnmanagedMemoryStream()"不符合CLS。