個人的なメモ

めもめも.

VC++ DLLサンプル

DLL側

#include "pch.h"
#include "stdio.h"
#include <windows.h>

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

extern "C" __declspec(dllexport) int plus(int x, int y)
{
    return (x + y);
}

extern "C" __declspec(dllexport) void print_hoge(void)
{
    printf("HOGE\n");

    int msgboxID = MessageBox(
        NULL,
        L"message!!",
        L"Title",
        MB_ICONEXCLAMATION | MB_YESNO
    );
}

DLLを呼び出す側

#include <iostream>
#include <windows.h>

typedef int (*FUNC1)(int x, int y);
typedef int (*FUNC2)();


int main()
{
    std::cout << "Hello World!\n";

    HMODULE hModule = LoadLibrary(L"sample_dll.dll");
    if (NULL == hModule)
    {
        std::cout << "Failed load library!\n";
        return 1;
    }
    std::cout << "Success load library!\n";

    FUNC1 func = (FUNC1)GetProcAddress(hModule, "plus");
    if (NULL == func)
    {
        std::cout << "Failed load function!\n";
        return 2;
    }
    std::cout << "Success load function!\n";

    std::cout << func(1, 2);

    FUNC2 func2 = (FUNC2)GetProcAddress(hModule, "print_hoge");
    if (NULL == func2)
    {
        std::cout << "Failed load function!\n";
        return 2;
    }
    std::cout << "Success load function!\n";

    func2();

    while (1) {}
}