Win32 C++程式碼快速驗證模板

倚剑问天發表於2024-09-04

DLL模板

#include <windows.h>

#include <algorithm>
#include <array>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>

using namespace std;

#pragma warning(disable : 4996)

#define LOG(_text, ...) PrintDebugString(L"[demo]" _text L"\r\n", __VA_ARGS__)

void PrintDebugString(LPCWSTR lpwszFormat, ...);

namespace {
/*
 * 0 ProcessAttach NoCall
 * 1 ProcessAttach Called
 */
LONG volatile g_iDllMainProcessAttachFlag = 0;
}  // namespace

extern "C" __declspec(dllexport) void ExportedFunction() {}

void PrintDebugString(LPCWSTR lpwszFormat, ...) {
  va_list args;
  va_start(args, lpwszFormat);

  WCHAR wszBuffer[4096] = {L"FcDebug:"};
  if (_vswprintf(wszBuffer + wcslen(wszBuffer), lpwszFormat, args) < 0) {
    OutputDebugStringW(L"FcDebug: Input String is INVALID !!!");
  }

  va_end(args);
  OutputDebugStringW(wszBuffer);
}

void LibraryHandler_ProcAttach(HANDLE hModule) { LOG("Attach Begin!!"); }

void LibraryHandler_ProcDetach(HANDLE hModule) { LOG("Detach Begin!!"); }

BOOL WINAPI DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpvReserved) {
  // DisableThreadLibraryCalls(hModule);

  switch (dwReason) {
    case DLL_PROCESS_ATTACH: {
      if (0 == InterlockedCompareExchange(&g_iDllMainProcessAttachFlag, 1, 0)) {
        auto threadObj = std::thread(
            [hModule]() -> void { LibraryHandler_ProcAttach(hModule); });
        threadObj.detach();
      }
      break;
    }
    case DLL_PROCESS_DETACH: {
      LibraryHandler_ProcDetach(hModule);
      break;
    }
    case DLL_THREAD_ATTACH:
      break;
    case DLL_THREAD_DETACH:
      break;
  }

  return TRUE;
}

相關文章