当我取消注释创建位图的代码行时,我遇到了第一次异常错误。我以与我制作的其他 Sprite 相同的方式创建了这个 Sprite 表 BMP。错误信息是这样的:
First-chance exception at 0x004788ca in HenwayRevamped.exe: 0xC0000005: Access violation writing location 0x02224000.
我正在运行一个基于 Michael Morrison 的 GameEngine 类构建的游戏。我对这个错误做了几个小时的研究,包括许多 StackOverflow 线程和 this handy site但我仍然不确定问题出在哪里。这是函数调用:
// Create a bitmap from a resource
Bitmap::Bitmap(HDC hDC, UINT uiResID, HINSTANCE hInstance)
: m_hBitmap(NULL), m_iWidth(0), m_iHeight(0)
{
Create(hDC, uiResID, hInstance);
}
这是函数:
BOOL Bitmap::Create(HDC hDC, UINT uiResID, HINSTANCE hInstance)
{
// Free any previous DIB info
Free();
// Find the bitmap resource
HRSRC hResInfo = FindResource(hInstance, MAKEINTRESOURCE(uiResID), RT_BITMAP);
if (hResInfo == NULL)
return FALSE;
// Load the bitmap resource
HGLOBAL hMemBitmap = LoadResource(hInstance, hResInfo);
if (hMemBitmap == NULL)
return FALSE;
// Lock the resource and access the entire bitmap image
PBYTE pBitmapImage = (BYTE*)LockResource(hMemBitmap);
if (pBitmapImage == NULL)
{
FreeResource(hMemBitmap);
return FALSE;
}
// Store the width and height of the bitmap
BITMAPINFO* pBitmapInfo = (BITMAPINFO*)pBitmapImage;
m_iWidth = (int)pBitmapInfo->bmiHeader.biWidth;
m_iHeight = (int)pBitmapInfo->bmiHeader.biHeight;
// Get a handle to the bitmap and copy the image bits
PBYTE pBitmapBits;
m_hBitmap = CreateDIBSection(hDC, pBitmapInfo, DIB_RGB_COLORS,
(PVOID*)&pBitmapBits, NULL, 0);
if ((m_hBitmap != NULL) && (pBitmapBits != NULL))
{
const PBYTE pTempBits = pBitmapImage + pBitmapInfo->bmiHeader.biSize +
pBitmapInfo->bmiHeader.biClrUsed * sizeof(RGBQUAD);
CopyMemory(pBitmapBits, pTempBits, pBitmapInfo->bmiHeader.biSizeImage);
// Unlock and free the bitmap graphics object
UnlockResource(hMemBitmap);
FreeResource(hMemBitmap);
return TRUE;
}
// Something went wrong, so cleanup everything
UnlockResource(hMemBitmap);
FreeResource(hMemBitmap);
Free();
return FALSE;
}
此外,这是我的带有本地窗口的 IDE 的屏幕截图。装订线中的绿色箭头图标指向抛出异常的行:
Image Hosted by ImageShack.us http://imageshack.us/a/img341/7678/20121216010703am.png
是我的设备环境出了问题吗? hDC 变量下的红色感叹号图标看起来可能指向问题,但它分配了一个句柄,所以我不确定。我已经没有想法了,正在求助于大师。
最佳答案
访问冲突发生在写入时,这表明您正在溢出目标缓冲区。有许多不同类型的位图格式,因此计算缓冲区的正确大小可能很困难。您的代码确实适用于某些位图,因此我怀疑您对位深度、颜色表大小、对齐方式或类似这些方面的某些假设有错误的假设。
只要有可能,您也可以让 Windows 来完成这项工作:
BOOL Bitmap::Create2(UINT uiResID, HINSTANCE hInstance) {
BOOL bSuccess = FALSE;
Free();
m_hBitmap = reinterpret_cast<HBITMAP>(
::LoadImage(hInstance, MAKEINTRESOURCE(uiResID), IMAGE_BITMAP,
0, 0, LR_CREATEDIBSECTION));
if (m_hBitmap != NULL) {
BITMAP bmp;
if (::GetObject(m_hBitmap, sizeof(bmp), &bmp) == sizeof(bmp)) {
m_iWidth = bmp.bmWidth;
m_iHeight = bmp.bmHeight;
bSuccess = TRUE;
}
}
return bSuccess;
}
这应该适用于所有有效的位图。请注意,您不再需要将句柄传递给 DC。
关于c++ - 0xC0000005 : Access violation after calling CopyMemory(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13899209/