OutputDebugStringA 生成异常 DBG_PRINTEXCEPTION_C(win10 中的W 版本 - DBG_PRINTEXCEPTION_WIDE_C),带有 2 个参数 -(字符串长度,字符 + 1,字符串指针) - 结果我们可以自己处理这个异常(系统此异常的默认处理程序为 this)。
将OutputDebugString 重定向到控制台的示例处理程序:
LONG NTAPI VexHandler(PEXCEPTION_POINTERS ExceptionInfo)
{
PEXCEPTION_RECORD ExceptionRecord = ExceptionInfo->ExceptionRecord;
switch (ExceptionRecord->ExceptionCode)
{
case DBG_PRINTEXCEPTION_WIDE_C:
case DBG_PRINTEXCEPTION_C:
if (ExceptionRecord->NumberParameters >= 2)
{
ULONG len = (ULONG)ExceptionRecord->ExceptionInformation[0];
union {
ULONG_PTR up;
PCWSTR pwz;
PCSTR psz;
};
up = ExceptionRecord->ExceptionInformation[1];
HANDLE hOut = GetStdHandle(STD_ERROR_HANDLE);
if (ExceptionRecord->ExceptionCode == DBG_PRINTEXCEPTION_C)
{
// localized text will be incorrect displayed, if used not CP_OEMCP encoding
// WriteConsoleA(hOut, psz, len, &len, 0);
// assume CP_ACP encoding
if (ULONG n = MultiByteToWideChar(CP_ACP, 0, psz, len, 0, 0))
{
PWSTR wz = (PWSTR)alloca(n * sizeof(WCHAR));
if (len = MultiByteToWideChar(CP_ACP, 0, psz, len, wz, n))
{
pwz = wz;
}
}
}
if (len)
{
WriteConsoleW(hOut, pwz, len - 1, &len, 0);
}
}
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
设置这个处理程序需要调用:
AddVectoredExceptionHandler(TRUE, VexHandler);
OutputDebugString 的系统实现类似于here - 它确实使用这个参数调用了RaiseException,只是在异常处理程序中而不是MessageBox - 代码描述为here。