dll入門簡單實例(動態鏈接庫)

方式一:非空項目

1、創建win32項目, 選擇Dll應用程序



2、新建dllexport.h

// dllexport.h

#ifdef WIN32
    #ifdef DLL_TEST_EXPORT
        #define DLL_TEST_API __declspec(dllexport)
    #else
        #define DLL_TEST_API __declspec(dllimport)
    #endif
#endif



3、新建ncDllTest.h

// ncDllTest.h

// #設置預處理器
// ADD_DEFINITIONS("-DLL_SAMPLE_EXPORT")
#define DLL_TEST_EXPORT
#include "dllexport.h"
extern "C" DLL_TEST_API void TestDLL(int);



4、新建ncDllTest.cpp

// ncDllTest.cpp

#include "stdafx.h"
#include "ncDllTest.h"
#include <stdio.h>
void TestDLL(int arg)
{
    printf("DLL output arg %d\n", arg);
}



5、F7編譯即可生成MyDll3.dll



方式二:空項目

1、創建win32項目, 選擇Dll應用程序,附加選項爲空項目




2、新建ncDllSimple.h

#ifndef __NC_DLL_SAMPLE_H__
#define __NC_DLL_SAMPLE_H__
#ifdef WIN32
    #ifdef DLL_SAMPLE_EXPORT
        #define DLL_SAMPLE_API __declspec(dllexport)
    #else
        #define DLL_SAMPLE_API __declspec(dllimport)
    #endif
#endif
extern "C" DLL_SAMPLE_API void TestDLL(int);
#endif



3、新建ncDllSimple.cpp

#pragma once
#include <windows.h>
#include <stdio.h>
// #設置預處理器
// ADD_DEFINITIONS("-DLL_SAMPLE_EXPORT")
#define DLL_SAMPLE_EXPORT
#include "ncDLLSample.h"
// DllMain可寫可不寫, 不寫系統會調用默認的
// BOOL APIENTRY DllMain(HANDLE 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;
// }

void TestDLL(int arg)
{
    printf("DLL output arg %d\n", arg);
}



4、F7編譯生成MyDll4.dll



測試三

1、創建win32項目, 選擇控制檯應用程序,附加選項爲空項目



2、新建main.cpp

#include <iostream>
#include <windows.h>
#include <tchar.h>
typedef void (*DLLFunc)(int);
int main()
{
    HINSTANCE hInstLibrary = LoadLibrary(_T("../Debug/MyDll.dll")); // dll的相對路徑
    if (hInstLibrary == NULL)
    {
        FreeLibrary(hInstLibrary);
        printf("LoadLibrary err\n");
        getchar();
        return 1;
    }
    DLLFunc dllFunc = (DLLFunc)GetProcAddress(hInstLibrary, "TestDLL");
    if (dllFunc == NULL)
    {
        FreeLibrary(hInstLibrary);
        printf("GetProcAddress err\n");
        getchar();
        return 1;
    }
    dllFunc(123);
    FreeLibrary(hInstLibrary);
    getchar();
    return 1;
}



3、F5編譯運行



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章