2008-09-03 19 views

答えて

6

あなたは(クラスは、.NET FCL 2.0以降に存在する)代わりにUnmanagedMemoryStream()を使用する場合は、コピーを回避することができます。 MemoryStreamのように、それはIO.Streamのサブクラスであり、すべての通常のストリーム操作を持ちます。

クラスのMicrosoftの説明は次のとおりです。

は、マネージコードからアンマネージメモリブロックへのアクセスを提供します。

あなたが知る必要があることはほとんどわかります。 UnmanagedMemoryStream()はCLSに準拠していないことに注意してください。

+0

注:この回答は安全でないコードでのみ機能します。安全でないフラグを指定してコンパイルしないと、バイト配列にデータをマーシャリングし、そのバイト配列をストリームにラップすることによって、より良い運を得ることができます。参照: http://stackoverflow.com/a/11660831/684852 データの長さ(ポインタの元のユニコード文字列のバイト数)を知る必要があります。 例: byte [] dataArray = new byte [dataLength]; Marshal.Copy(szUnicodeString、dataArray、0、dataLength); MemoryStream stream =新しいMemoryStream(dataArray); ' –

1

私はメモリをコピーしていた場合、私は次のように働くだろうと思う:


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); 
}
関連する問題