CImage::Load() from memory without using 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
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01