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

时间:2016-08-01 05:12:56

标签: c++ winapi mfc atl

我正在显示来自相机的即时取景视频。我下载的每一帧都是一个我必须分配的字节数组(pImageData)。

现在,要显示,我正在使用CImage(MFC)。 但是,我找到的所有样本都基于使用GlobalAlloc,另一个是memcpy和CreateStreamOnHGlobal。

我想避免再做一次分配/释放和内存复制。每帧超过2mb,我推动30 fps!

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

以下是代码:

// 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);

1 个答案:

答案 0 :(得分:0)

感谢Hans指出了我不知道的SHCreateMemStream。 代码更清晰,但仍不确定SHCreateMemStream是否在内部创建副本(文档不清楚)

[编辑]根据Jonathan的评论,看起来仍然需要在内部制作副本。当.. ..

最终代码

// 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