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

查看:40
本文介绍了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] 根据 Jonathan 的评论,看起来它仍然需要在内部制作副本.党..

[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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆