我正在尝试初始化directX,但由于某种原因它无法创建d3d设备。 它编译正确,但显示最后一个消息框(“无法创建D3D设备”)
调试时:
- d3dObject 0x00000000 IDirect3D9 *
- IUnknown {...} IUnknown
__vfptr CXX0030:错误:无法计算表达式
#include <d3d9.h>
#include <d3dx9.h>
#include <windows.h>
HWND hMainWindow;
IDirect3D9 *d3dObject = 0;
IDirect3DDevice9 *d3dDevice = 0;
bool InitDirectX()
{
d3dObject = Direct3DCreate9(D3D_SDK_VERSION);
if( !d3dObject )
{
MessageBox(0, "Can't create Direct3D Object", "Error", MB_ICONSTOP);
PostQuitMessage(0);
}
D3DDISPLAYMODE mode;
d3dObject->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &mode);
d3dObject->CheckDeviceType(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, mode.Format, mode.Format, true);
d3dObject->CheckDeviceType(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, D3DFMT_X8R8G8B8, false);
D3DCAPS9 caps;
d3dObject->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps);
DWORD devBehaviorFlags = 0;
if( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT )
devBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
else
devBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// If pure device and HW T&L supported
if( caps.DevCaps & D3DDEVCAPS_PUREDEVICE &&
devBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING)
devBehaviorFlags |= D3DCREATE_PUREDEVICE;
D3DPRESENT_PARAMETERS d3dpp;
d3dpp.BackBufferWidth = 800;
d3dpp.BackBufferHeight = 600;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.BackBufferCount = 1;
d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
d3dpp.MultiSampleQuality = 0;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = hMainWindow;
d3dpp.Windowed = true;
d3dpp.EnableAutoDepthStencil = true;
d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
d3dpp.Flags = 0;
d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
if(!d3dObject->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hMainWindow, devBehaviorFlags, &d3dpp, &d3dDevice))
{
::MessageBox(0, "Can't create D3D device", "Error", MB_ICONSTOP);
return false;
}
return true;
}
答案 0 :(得分:2)
IDirect3D9 :: CreateDevice返回HRESULT而不是bool。 检查设备是否已创建的正确方法是使用SUCCEEDED或FAILED宏:
HRESULT hr = d3dObject->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hMainWindow, devBehaviorFlags, &d3dpp, &d3dDevice);
if( FAILED(hr) )
{
// hr will be one of the D3DERR_ values
::MessageBox(0, "Can't create D3D device", "Error", MB_ICONSTOP);
return false;
}
答案 1 :(得分:0)
调试D3D9的最佳方法是启用调试DLL,如上一个答案所述。不幸的是,Windows 7和更低版本支持D3D9调试DLL。如果您使用的是Windows 8或更高版本,那么最好的选择是转到D3D11(无论如何,您都可以这样做)。根据您的描述,您说程序显示了第二个MessageBox,这意味着对CreateDevice的调用已失败。但是您提到调试器说d3dObject为空。我将假设您获得此读数的位置是在调用Direct3DCreate9之前,否则您的程序将在第二个消息框出现之前崩溃。
在您的特定情况下,CreateDevice实际上是成功的,因为HRESULT为0表示成功(S_OK),因此,如前一个答案所述,请使用SUCCEEDED或FAILED宏检查HRESULT状态,而不是将thrm解释为bool。