如何将 IntPtr 转换为 Stream?
-
09-06-2019 - |
题
class Foo
{
static bool Bar(Stream^ stream);
};
class FooWrapper
{
bool Bar(LPCWSTR szUnicodeString)
{
return Foo::Bar(??);
}
};
MemoryStream
将采取 byte[]
但我会 喜欢 如果可能的话,在不复制数据的情况下执行此操作。
解决方案
如果您使用 UnmanagedMemoryStream()
相反(类存在于 .NET 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);
}
不隶属于 StackOverflow