2012-07-26 97 views
2

我正試圖從剪貼板中取設備無關位圖。我很清楚,這可以通過內嵌在.NET Framework中的Clipboard.GetData函數完成,但由於它非常麻煩(如網上許多地方所記錄),我只想使用這些API。將指針轉換成MemoryStream?

我寫了下面的代碼,它的作品。

//i can correctly cast this to a MemoryStream 
MemoryStream ms = Clipboard.GetData("DeviceIndependentBitmap") as MemoryStream; 

但我想用它與API,它只是返回一個指向流的指針(IntPtr)。我查看了UnmanagedMemoryStream,但未能理解如何將IntPtr正確轉換爲該格式。

這是我的API代碼(使用GetClipboardData API,其中CF_DIB格式設置爲其參數)。

IntPtr p = GetClipboardData(8); 
//what do I do from here to get a MemoryStream from this pointer? 

我有點困惑。我已經自己研究過它,但不能提出一些有用的東西。

回答

6

正如你所說,你可以使用UnmanagedMemoryStream(byte* pointer, long length)並使用它,你應該有一個指針和字節的長度。因此,您可以使用IntPtr.ToPointer()方法獲取指針,但應該知道內存內容的長度。

UnmanagedMemoryStream unmanagedmemstream = UnmanagedMemoryStream(p.ToPointer(), 100); 

有檢索字節數組另一種方法,而且在這裏你應該知道,你想要的內存字節lenght,這是Marshal.Copy(IntPtr source, byte[] destination, int startIndex,int length)

byte[] buffer = new byte[100]; 
Marshal.Copy(p , buffer, 0, buffer.Lenght);