[英]How make a copy of pointer value in c++ and prevent crash
我有一个 function 使用 DirectX 11 返回屏幕特定 X、Y 坐标的像素颜色。
function 使用方法“AcquireNextFrame”,如果当前帧等于前一帧,不幸失败 (DXGI_ERROR_WAIT_TIMEOUT)。
因此,一些用户建议复制“IDXGIOutputDuplication”值,但经过一些尝试,我看到开始不稳定,就像其他用户在这些情况下所说的那样。
出于这个原因,我尝试使用以下变量对代码的其他部分进行“备份”:“gpuTexPrevious”和“cpuTexPrevious”:
ID3D11Texture2D* gpuTexPrevious = nullptr;
ID3D11Texture2D* cpuTexPrevious = nullptr;
RGBTRIPLE CaptureNext(int X, int Y) {
bool NewFrame;
RGBTRIPLE rgb;
rgb.rgbtBlue = 0;
rgb.rgbtGreen = 0;
rgb.rgbtBlue = 0;
HRESULT hr;
IDXGIResource* deskRes = nullptr;
DXGI_OUTDUPL_FRAME_INFO frameInfo;
hr = DeskDupl->AcquireNextFrame(0, &frameInfo, &deskRes);
if (hr == DXGI_ERROR_WAIT_TIMEOUT) {
LF::Log_Update(" DXGI_ERROR_WAIT_TIMEOUT");
NewFrame = false;
}
else
NewFrame = true;
ID3D11Texture2D* gpuTex = nullptr;
ID3D11Texture2D* cpuTex = nullptr;
if (NewFrame)
{
hr = deskRes->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&gpuTex);
deskRes->Release();
deskRes = nullptr;
if (FAILED(hr)) {
// not expected
return rgb;
}
D3D11_TEXTURE2D_DESC desc;
gpuTex->GetDesc(&desc);
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.MiscFlags = 0; // D3D11_RESOURCE_MISC_GDI_COMPATIBLE ?
hr = D3DDeviceTest->CreateTexture2D(&desc, nullptr, &cpuTex);
memcpy(&cpuTexPrevious, &cpuTex, sizeof(ID3D11Texture2D));
}
else
{
memcpy(&gpuTex, &gpuTexPrevious, sizeof(ID3D11Texture2D));
memcpy(&cpuTex, &cpuTexPrevious, sizeof(ID3D11Texture2D));
}
D3D11_BOX srcBox;
srcBox.left = X;
srcBox.right = X + 1;
srcBox.bottom = Y + 1;
srcBox.top = Y;
srcBox.front = 0;
srcBox.back = 1;
D3DDeviceContextTest->CopySubresourceRegion(cpuTex, 0, 0, 0, 0, gpuTex, 0, &srcBox);
memcpy(&gpuTexPrevious, &gpuTex,sizeof(ID3D11Texture2D));
D3D11_MAPPED_SUBRESOURCE sr;
// crash here when NewFrame = false
hr = D3DDeviceContextTest->Map(cpuTex, 0, D3D11_MAP_READ, 0, &sr);
COLORREF* pPixels = (COLORREF*)sr.pData;
rgb.rgbtRed = (pPixels[0] >> 16) & 0xff;
rgb.rgbtGreen = (pPixels[0] >> 8) & 0xff;
rgb.rgbtBlue = pPixels[0] & 0xff;
D3DDeviceContextTest->Unmap(cpuTex, 0);
cpuTex->Release();
gpuTex->Release();
hr = DeskDupl->ReleaseFrame();
return rgb;
}
直到“AcquireNextFrame”返回 OK 我的代码工作正常,但是当返回“DXGI_ERROR_WAIT_TIMEOUT”
在这一行崩溃:
hr = D3DDeviceContextTest->Map(cpuTex, 0, D3D11_MAP_READ, 0, &sr);
所以我认为我的不是复制指针值的正确方法。
你能建议我另一种方式吗?
谢谢 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.