LoginSignup
8
9

More than 5 years have passed since last update.

WindowsのGUIアプリやDLL内からのprintfを画面表示する方法

Last updated at Posted at 2018-11-08

AllocConsole()を使います

AllocConsole()を使うとコンソールアプリでなくとも新規にコンソールを開くことが出来ます。
さらに標準出力(標準エラー出力)をそのコンソールに向けることが出来るので、printfデバッグが出来て色々捗ります。

これはDLLの実装使例です。

mydll.c
#include <windows.h>
#include <stdio.h>

__declspec(dllexport) void __cdecl Function1(void) {
    printf_s("%s\n", __func__); /* 標準出力 */
    /* または */
    fprintf_s(stdout, "%s\n", __func__); /* 標準出力 */
}

__declspec(dllexport) void __cdecl Function2(void) {
    fprintf_s(stderr, "%s\n", __func__); /* 標準エラー出力 */
}

/* 新規にコンソールを開く */
void CreateConsole(void) {
    FILE* fp;
    AllocConsole();
    freopen_s(&fp, "CONOUT$", "w", stdout); /* 標準出力(stdout)を新しいコンソールに向ける */
    freopen_s(&fp, "CONOUT$", "w", stderr); /* 標準エラー出力(stderr)を新しいコンソールに向ける */
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
    switch (fdwReason) {
    case DLL_PROCESS_ATTACH:
        CreateConsole();
        break;
    }
    return TRUE;
}

参考にしたページ

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9