class Foo
{
static bool Bar(Stream^ stream);
};
class FooWrapper
{
bool Bar(LPCWSTR szUnicodeString)
{
return Foo::Bar(??);
}
};
MemoryStream
将采取byte[]
但我喜欢做到这一点不复制如果可能的数据。如何将IntPtr转换为流?
class Foo
{
static bool Bar(Stream^ stream);
};
class FooWrapper
{
bool Bar(LPCWSTR szUnicodeString)
{
return Foo::Bar(??);
}
};
MemoryStream
将采取byte[]
但我喜欢做到这一点不复制如果可能的数据。如何将IntPtr转换为流?
可以避开副本,如果您使用的UnmanagedMemoryStream()
代替(类.NET FCL 2.0及更高版本存在)。像MemoryStream
一样,它是IO.Stream
的子类,并具有所有常用的流操作。
微软之类的描述是:
提供了获取从托管代码非托管内存块。
这几乎告诉你你需要知道什么。请注意0不符合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);
}
注意:此答案仅适用于不安全的代码。如果您不使用不安全标志进行编译,将数据编组为字节数组,然后将该数组包装到流中,可能会带来更好的运气。请参阅: http://stackoverflow.com/a/11660831/684852 尽管您需要知道数据的长度(指针中原始unicode字符串中的字节数)。 例如: `byte [] dataArray = new byte [dataLength]; Marshal.Copy(szUnicodeString,dataArray,0,dataLength); MemoryStream stream = new MemoryStream(dataArray);` – 2013-12-22 21:57:57