我使用的是使用函数OutputDebugString()的第三方库,在读取MSDN文档时,它似乎表明这是为了打印到调试器。
但在我的例子中,这是不方便的,如果没有连接调试器,是否有读取输出的方法?
如果是我的LIB,我更希望当用户传递--debug或类似的时候,输出转到stdout/stderr,但是由于它不是,我正在寻找其他方法将这个信息传递到控制台(或文件),而不需要连接调试器。
发布于 2017-01-05 09:01:35
OutputDebugStringA生成带有两个参数的异常DBG_PRINTEXCEPTION_C ( win10 -DBG_PRINTEXCEPTION_WIDE_C中的W版本)--(字符串长度以字符+ 1表示,字符串指针)--因此我们可以自己处理这个异常(此异常的系统默认处理程序为do 这)。
将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类似于这里的系统实现--它实际上调用了带有此参数的RaiseException,只有在异常处理程序中,而不是在MessageBox --代码描述了这里。
https://stackoverflow.com/questions/41465986
复制相似问题