簡體   English   中英

在 VS2017 中使用 integer 作為 OutputDebugString

[英]Using a integer for OutputDebugString in VS2017

我一直在 web 上搜索一段時間,了解如何使用 OutputDebugString() 將 output 和 integer 或可選的浮點數。 如果我可以使用此命令將我的調試數據從我的外部可執行文件直接寫入控制台,那會更容易。 但是我只讓它與 const char 一起工作。 我發現的解決方案已過時 我嘗試直接從 web 復制並粘貼代碼,但沒有用。 即使修改了代碼,我也無法正確地進行類型轉換。 有沒有人可以幫助我盡可能干凈地將某些內容類型轉換為 OutputDebugString,它僅用於調試目的,所以我寧願保持代碼簡短且易於閱讀,也不願使用更復雜和笨重的類型轉換 IF 。 非常感謝!

提供替代解決方案。 下面的function封裝了可以接受格式化arguments的OutputDebugString。

#include <vector>
#include <string>    
void DbgMsg(const char * zcFormat, ...)
{
    // initialize use of the variable argument array
    va_list vaArgs;
    va_start(vaArgs, zcFormat);

    // reliably acquire the size
    // from a copy of the variable argument array
    // and a functionally reliable call to mock the formatting
    va_list vaArgsCopy;
    va_copy(vaArgsCopy, vaArgs);
    const int iLen = std::vsnprintf(NULL, 0, zcFormat, vaArgsCopy);
    va_end(vaArgsCopy);

    // return a formatted string without risking memory mismanagement
    // and without assuming any compiler or platform specific behavior
    std::vector<char> zc(iLen + 1);
    std::vsnprintf(zc.data(), zc.size(), zcFormat, vaArgs);
    va_end(vaArgs);
    std::string strText(zc.data(), iLen);

    OutputDebugStringA(strText.c_str());
}

例如,下面的代碼顯示了如何通過 DbgMsg() 通過 OutputDebugString 打印一個 integer 變量。

int foo=12;
DbgMsg(" foo=%d", foo);

OutputDebugString 只能接受字符串,如果你想格式化 output,你必須在將它提供給 OutputDebugString 之前自己做。 如果您使用的是 MSVC,我建議您使用 _CrtDbgReport 或 _CrtDbgReportW。 對於支持可變參數宏的最新版本的 MSVC,我使用以下內容:

#if !defined(_RPTW)
#if defined(_DEBUG)
#define _RPTW(pszFmt, ...) _CrtDbgReportW(_CRT_WARN, NULL, __LINE__, NULL, (pszFmt), __VA_ARGS__)
#define _RPTW_(dest, fmt, ...) _CrtDbgReportW((dest), NULL, __LINE__, NULL, (pszFmt), __VA_ARGS__)
#else
#define _RPTW(pszFmt, ...)
#define _RPTW(dest, pszFmt)
#endif
#endif // #if !defined(_RPTW)

#if !defined(_RPTA)
#if defined(_DEBUG)
#define _RPTA(pszFmt, ...) _CrtDbgReport(_CRT_WARN, NULL, __LINE__, NULL, (pszFmt), __VA_ARGS__)
#define _RPTA_(dest, fmt, ...) _CrtDbgReport((dest), NULL, __LINE__, NULL, (pszFmt), __VA_ARGS__)
#else
#define _RPTA(pszFmt, ...)
#define _RPTA_(dest, pszFmt)
#endif
#endif // #if !defined(_RPTA)

#if !defined(_RPTT)
#if defined(_UNICODE)
#define _RPTT _RPTW
#define _RPTT_ _RPTW_
#else
#define _RPTT _RPTA
#define _RPTT_ _RPTA_
#endif
#endif // #if !defined(_RPTT)

第二個 forms 允許提供不同級別的報告(_CRT_ASSERT 或 c_CRT_ERROR 而不是 _CRT_WARN)

我建議像這樣使用 sprintf :

// issues with the int x, let's output and look at it in DebugView
char msg[255] = {0};
sprintf(msg, ">> Watch out x=%d\n", x);
OutputDebugString(msg);

也許我不明白這個問題,但這就是我快速轉儲整數的方式。 老實說,我不知道 SoronelHaetir 列出的這些宏,但實際上你必須自己格式化。 所以我希望這會有所幫助並且非常簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM