dll入门简单实例(动态链接库)

这篇博客介绍了如何创建和使用DLL动态链接库。通过两种方式创建DLL项目,并展示了如何在控制台应用程序中调用DLL中的函数进行测试。详细步骤包括定义头文件、实现函数、编译DLL以及在主程序中加载和调用DLL函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式一:非空项目

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编译运行



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值