wpf 将指针转换为 MemoryStream?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11660643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a pointer into a MemoryStream?
提问by Mathias Lykkegaard Lorenzen
I am trying to fetch a Device Independent Bitmapfrom the clipboard. I am well-aware that this can be done through the Clipboard.GetData function inbuilt in the .NET Framework, but since it is very buggy (as documented many places on the web), I want to use the APIs only.
我正在尝试从剪贴板中获取与设备无关的位图。我很清楚这可以通过 .NET Framework 中内置的 Clipboard.GetData 函数来完成,但由于它非常有问题(如网络上的许多地方所记录),我只想使用 API。
I have written the following code which works.
我编写了以下有效的代码。
//i can correctly cast this to a MemoryStream
MemoryStream ms = Clipboard.GetData("DeviceIndependentBitmap") as MemoryStream;
But I want to use it with the APIs, which just return a pointer (an IntPtr) that point to the stream somehow. I took a look at the UnmanagedMemoryStreambut fail to understand how to correctly convert an IntPtrinto that.
但是我想将它与 API 一起使用,它只返回一个以某种方式指向流的指针(一个 IntPtr)。我查看了UnmanagedMemoryStream但无法理解如何正确地将它转换IntPtr为它。
Here's my API code (using the GetClipboardDataAPI where the CF_DIBformat is set as its argument).
这是我的 API 代码(使用GetClipboardDataAPI,其中CF_DIB格式设置为其参数)。
IntPtr p = GetClipboardData(8);
//what do I do from here to get a MemoryStream from this pointer?
I'm a bit confused. I already researched it myself, but couldn't come up with something useful.
我有点困惑。我自己已经研究过了,但想不出有用的东西。
回答by Omar
As you said you can use UnmanagedMemoryStream(byte* pointer, long length)and to use it you should have a pointer and the length of the bytes. So you can use IntPtr.ToPointer()method to get the pointer, but you should know the length of the memory content.
正如您所说,您可以使用UnmanagedMemoryStream(byte* pointer, long length)并使用它,您应该有一个指针和字节长度。所以你可以使用IntPtr.ToPointer()方法来获取指针,但你应该知道内存内容的长度。
UnmanagedMemoryStream unmanagedmemstream = UnmanagedMemoryStream(p.ToPointer(), 100);
There is another method to retrieve an array of bytes, but also here you should know the length of the memory bytes that you want and it is Marshal.Copy(IntPtr source, byte[] destination, int startIndex,int length):
还有另一种方法来检索字节数组,但在这里你应该知道你想要的内存字节的长度,它是Marshal.Copy(IntPtr source, byte[] destination, int startIndex,int length):
byte[] buffer = new byte[100];
Marshal.Copy(p , buffer, 0, buffer.Length);

