gpt4 book ai didi

c++ - 控制台中的 OutputDebugString()

转载 作者:可可西里 更新时间:2023-11-01 14:14:23 30 4
gpt4 key购买 nike

我正在使用使用函数 OutputDebugString() 的第三方库,并且在阅读 MSDN 文档时,它似乎表明这是为了打印到调试器。

但这对我来说很不方便,如果没有连接调试器,有没有办法读取这个输出?

如果它是我的 LIB,我希望每当用户通过 --debug 或类似方式时输出转到 stdout/stderr,但因为不是我正在寻找其他方式来传递它无需连接调试器即可将信息发送到控制台(或文件)。

最佳答案

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 .

关于c++ - 控制台中的 OutputDebugString(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41465986/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com