سؤال

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

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

MemoryStream سوف تأخذ byte[] ولكن أود أن مثل للقيام بذلك دون نسخ البيانات إذا كان ذلك ممكنا.

هل كانت مفيدة؟

المحلول

يمكنك تجنب نسخ إذا كنت تستخدم UnmanagedMemoryStream() بدلا من ذلك (فئة موجودة في .صافي FCL 2.0 و في وقت لاحق).مثل MemoryStream, هو فئة فرعية من IO.Stream, و لديه كل تيار المعتاد العمليات.

مايكروسوفت وصف الطبقة:

يوفر الوصول غير المدارة كتل الذاكرة من التعليمات البرمجية المدارة.

الذي يقول لك ما تحتاج إلى معرفته.علما بأن UnmanagedMemoryStream() لا CLS المتوافقة.

نصائح أخرى

إذا كان لي أن نسخ الذاكرة أعتقد التالية سوف تعمل:


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);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top