gpt4 book ai didi

c++ - 提取图标Ex : works but occasionally crashes

转载 作者:太空狗 更新时间:2023-10-29 20:20:11 33 4
gpt4 key购买 nike

我正在从文件中提取图标并在对话框中显示它们

const LPCWSTR path = L"c:\path\to\file";
const UINT nIconsCheck = ExtractIconEx(path, -1, nullptr, nullptr, 0);
if(nIconsCheck > 0)
{
HICON *iconHandles=new HICON;
const UINT nIcons = ExtractIconEx(path, 0, iconHandles, nullptr, nIconsCheck);

if(nIcons == nIconsCheck && nIcons != unsigned(-1))
{

IconSelect iconSelect(this); //dialog
for(UINT i=0; i<nIcons; i++)
{
qDebug() << i;
iconSelect.addIcon(QtWin::fromHICON(iconHandles[i])); //fromHICON returns QPixmap
DestroyIcon(iconHandles[i]);
}

iconSelect.exec();
}
}

图标在对话框中正确加载,但有时会意外导致应用程序崩溃。

知道发生了什么吗?

Documentation on ExtractIconEx

编辑:感谢您快速而有用的回答。以下是我使用 atm 的完整工作代码:

// In my case I have a QString `filePath`
// `QString::toWCharArray` retrieves a non-0-terminated string,
// so append a 0 to `path`
std::vector<WCHAR> path(unsigned(filePath.length())+1);
filePath.toWCharArray(path.data());
path.at(path.size()-1) = 0;

// Get number of icons in selected file
UINT nIcons = ExtractIconEx(path.data(), -1, nullptr, nullptr, 0);

if(nIcons == 0)
{
// Try to find associated file that contains icon(s)
// If found, `path` is replaced with the new path
WORD index=0;
DestroyIcon(ExtractAssociatedIcon(GetModuleHandle(nullptr), path.data(), &index));
// Get number of icons in associated file
nIcons = ExtractIconEx(path.data(), -1, nullptr, nullptr, 0);
}

if(nIcons > 0)
{
// Get array of HICONs
std::vector<HICON> iconHandles(nIcons);
nIcons = ExtractIconEx(path.data(), 0, iconHandles.data(), nullptr, nIcons);

for(UINT i=0; i<nIcons; i++) // Using iconHandles.size() is possibly safer,
// but AFAIK nIcons always carries the correct value
{
// Use iconHandles[i]
// In Qt you can use QtWin::fromHICON(iconHandles[i]) to generate a QPixmap
DestroyIcon(iconHandles[i]);
}
}

最佳答案

HICON *iconHandles=new HICON;

这里您只分配了一个HICON 对象。如果给定文件中有多个图标,则对 ExtractIconEx() 的下一次调用会通过写入超出分配的内存来创建缓冲区溢出。你已经进入了未定义行为的黑暗世界。

要解决此问题,您可以使用 std::vector像这样:

std::vector<HICON> iconHandles(nIconsCheck); 
const UINT nIcons = ExtractIconEx(path, 0, iconHandles.data(), nullptr, iconHandles.size());
iconHandles.resize(nIcons); // Resize to the actual number of icons.

// Instead of: if(nIcons == nIconsCheck && nIcons != unsigned(-1))
if(!iconHandles.empty())
{
// Use icons
}

这比手动分配有优势,您不需要删除分配的内存。 vector 析构函数将在作用域结束时自动执行此操作。尽管您仍然需要为每个图标句柄调用 DestroyIcon()

关于c++ - 提取图标Ex : works but occasionally crashes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53031482/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com