4.6 Debugging Direct3D Applications
In order to shorten the code and minimize distractions, we omit most error handling in this book. However, we do implement a macro to check the HRESULT return codes returned by many Direct3D functions. Our macro is defined as follows in d3dUtil.h:
1 #if defined(DEBUG) | defined(_DEBUG)
2 #ifndef HR
3 #define HR(x) \
4 { \
5 HRESULT hr = (x); \
6 if(FAILED(hr)) \
7 { \
8 DXTrace(__FILE__, (DWORD)__LINE__, hr, L#x, true); \
9 } \
10 }
11 #endif
12 #else
13 #ifndef HR
14 #define HR(x) (x)
15 #endif
16 #endif
If the returned function’s return code indicates failure, then we pass the return code into the DXTrace function (#include <dxerr.h>) and link dxerr.lib:
HRESULT WINAPI DXTraceW(const char* strFile, DWORD dwLine,
HRESULT hr, const WCHAR* strMsg, BOOL bPopMsgBox);
This function displays a nice message box indicating the file and line number where the error occurred, as well as a textual description of the error and the name of the function that generated the error; Figure 4.10 shows an example. Note that if you specify false for the last parameter of DXTrace, then instead of a message box, the debug info will be output to the Visual C++ output window. Observe that the macro HR does nothing if we are not in debug mode. Also, HR must be a macro and not a function; otherwise __FILE__ and __LINE__ would refer to the file and line of the function implementation instead of the file and line where the function HR was called.
Figure 4.10: The message box displayed by the DXTrace function if a Direct3D function returns an error.
Now we just use this macro to surround a Direct3D function that returns an HRESULT as this example shows:
HR(D3DX10CreateShaderResourceViewFromFile(md3dDevice,
L"grass.dds", 0, 0, &mGrassTexRV, 0 ));
This works well for debugging our demos, but a real application should handle errors more robustly.
Note The L#x turns the HR macro’s argument token into a Unicode string. In this way, we can output to the message box the function call that caused the error.

浙公网安备 33010602011771号