CImage::Load() 从内存而不使用 CreateStreamOnHGlobal

CImage::Load() from memory without using CreateStreamOnHGlobal(CImage::Load() 从内存而不使用 CreateStreamOnHGlobal)

本文介绍了CImage::Load() 从内存而不使用 CreateStreamOnHGlobal的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在显示来自摄像机的实时取景视频.我将每一帧下载到一个字节数组(pImageData)中,我必须分配它.

I am displaying a live view video from camera. Every frame I download into a byte array (pImageData) which I have to allocate.

现在,为了显示,我正在使用 CImage (MFC).但是,我找到的所有示例都基于使用 GlobalAlloc,还有另一个 memcpy 和 CreateStreamOnHGlobal.

Now, to display, I am using a CImage (MFC). However, all samples I find are based on using GlobalAlloc, yet another memcpy and CreateStreamOnHGlobal.

我想避免进行另一次分配/解除分配和内存复制.每帧超过 2mb,我正在推动 30 fps!

I'd like to avoid doing another allocation/deallocation and memory copy. Each frame is over 2mb and I am pushing 30 fps!

是否可以在基于非 HGLOBAL 的内存上创建 IStream?或者是否可以强制 Image::Load() 使用字节数组?

Is it possible to create an IStream on non-HGLOBAL based memory? OR Is it somehow possible to coerce Image::Load() to work with byte array?

代码如下:

// pImageData is an array with bytes, size is the sizeOfThatArray

CComPtr<IStream> stream;

HGLOBAL hMem = ::GlobalAlloc(GHND, size);
LPVOID pBuff = ::GlobalLock(hMem);

memcpy(pBuff, pImageData, size); // <-- would like to avoid this

::GlobalUnlock(hMem);

CreateStreamOnHGlobal(hMem, TRUE, &stream); // <-- or create stream on non-hglobal memory

CImage image;
image.Load(stream); // <-- Or load directly from pImageData

// .. display image

image.Destroy();

::GlobalFree(hMem);

推荐答案

感谢 Hans 指出 SHCreateMemStream,我不知道它存在.代码干净多了,但还是不确定SHCreateMemStream内部是否创建了副本(文档不清楚)

Thanks to Hans for pointing out SHCreateMemStream, which I did not know existed. The code is much cleaner, but still unsure whether SHCreateMemStream creates a copy internally (documentation is unclear)

根据乔纳森的评论,看起来它仍然需要在内部制作副本.当..

[edit] As per Jonathan' comments, looks like it still has to make a copy internally. Dang ..

最终代码

// pImageData is an array with bytes, size is the sizeOfThatArray

// Still not clear if this is making a copy internally
IStream* pMemStream = SHCreateMemStream(pImageData, size);

CComPtr<IStream> stream;

stream.Attach(pMemStream); // Need to Attach, otherwise ownership is not transferred and we leak memory

CImage image;
image.Load(stream); 

// .. display image

image.Destroy();

// No need for further cleanup, CComPtr does the job

这篇关于CImage::Load() 从内存而不使用 CreateStreamOnHGlobal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:CImage::Load() 从内存而不使用 CreateStreamOnHGlobal

基础教程推荐