1. 自定义类型: MyType
class MyType
{
public:
char m_strName[32];
int m_nAge;
};
2. 编写 natvis 文件: MyType.natvis
<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
<Type Name="MyType">
<DisplayString LegacyAddin="MyType.dll" Export="AddIn_MyType"></DisplayString>
</Type>
</AutoVisualizer>
3. 生成MyType.dll, 导出函数 AddIn_MyType
.h
typedef struct tagDEBUGHELPER
{
DWORD dwVersion;
HRESULT(WINAPI *ReadDebuggeeMemory)(struct tagDEBUGHELPER *pThis, DWORD dwAddr, DWORD nWant, VOID* pWhere, DWORD *nGot);
// from here only when dwVersion >= 0x20000
DWORDLONG(WINAPI *GetRealAddress)(struct tagDEBUGHELPER *pThis);
HRESULT(WINAPI *ReadDebuggeeMemoryEx)(struct tagDEBUGHELPER *pThis, DWORDLONG qwAddr, DWORD nWant, VOID* pWhere, DWORD *nGot);
int (WINAPI *GetProcessorType)(struct tagDEBUGHELPER *pThis);
} DEBUGHELPER;
typedef HRESULT(WINAPI *CUSTOMVIEWER)(DWORD dwAddress, DEBUGHELPER *pHelper, int nBase, BOOL bUniStrings, char *pResult, size_t max, DWORD reserved);
.cpp
static LRESULT ReadMemory(DEBUGHELPER *pHelper, DWORDLONG qwAddr, DWORD nSize, VOID* pBuf, DWORD *nGot)
{
if (pHelper->dwVersion < 0x20000)
{
// Visual C++ 6.0 version
if (pHelper->ReadDebuggeeMemory(pHelper, qwAddr, nSize, pBuf, nGot) != S_OK)
{
return E_FAIL;
}
}
else
{
if (pHelper->ReadDebuggeeMemoryEx(pHelper, qwAddr, nSize, pBuf, nGot) != S_OK)
{
return E_FAIL;
}
}
return S_OK;
}
__declspec(dllexport) HRESULT __stdcall AddIn_MyType(DWORD dwAddress, DEBUGHELPER *pHelper, int nBase, BOOL bUniStrings, char *pResult, size_t max, DWORD reserved)
{
// read file time from debuggee memory space
if (pHelper->dwVersion >= 0x20000)
{
dwAddress = pHelper->GetRealAddress(pHelper);
}
DWORD nGot;
char name[32] = { 0 };
int age = -1;
ReadMemory(pHelper, dwAddress, sizeof(name), name, &nGot);
ReadMemory(pHelper, dwAddress+ 32, sizeof(age), &age, &nGot);
sprintf_s(pResult, max, "name: %s, age: %d", name, age);
return S_OK;
}
4. 部署并测试
将
MyType.natvis 和 MyType.dll 一起放入下面文件夹中的其中之一
%VSINSTALLDIR%\Common7\Packages\Debugger\Visualizers (requires admin access)
%USERPROFILE%\My Documents\Visual Studio 2012\Visualizers\
VS extension folders
参考文章:https://stackoverflow.com/questions/11545418/how-to-write-a-custom-native-visualizer-dll-for-visual-studio-2012-debugger/11545420#11545420