C++之DLL的动态加载与静态加载初尝试

【环境:VS2019】

【编写一个DLL并导出函数】

1、新建动态链接库:V_BJZ

[framework.h]

#pragma once

#define WIN32_LEAN_AND_MEAN            
// 从 Windows 头文件中排除极少使用的内容
// Windows 头文件
#include <windows.h>
extern "C" _declspec(dllexport) int ReturnSum(int a, int b);
//导出声明,_declspec(dllexport)是关键字

[dll1.cpp]

#include "framework.h"
#include "pch.h"
int ReturnSum(int a, int b) //该DLL需要导出的函数功能:加法
{
    return a + b;
}

2、编译链接后的文件夹(划重点:之后要用的呀~)

【使用动态加载方式调用该函数】

1、新建项目V_DY

[DY.cpp]

#include<iostream>
#include<wtypes.h>
using namespace std;

typedef int(*pReturnSum)(int a, int b); 
//函数指针声明
int main() {
    HINSTANCE hDLL;    pReturnSum ReturnSum;    
    hDLL = LoadLibrary("G:\\Cplus_workspace\\V_1\\V_BJZ\\Debug\\V_BJZ.dll"); 
    //加载 DLL文件    
    if (hDLL == NULL) {
        cout << "Error!!!\n";
    }
    ReturnSum=(pReturnSum)GetProcAddress(hDLL,"ReturnSum");  
    //取DLL中的函数地址,以备调用 
    int a, b, sum;
    cin >> a >> b;
    sum = ReturnSum(a, b);
    cout<<"sum = "<<sum<<endl;        
    FreeLibrary(hDLL);    
    return 0;
} 

【使用静态加载的方式调用该函数】

1、新建项目V_DY2

2、将V_BJZ项目中的framework.h文件和V_BJZ.lib,V_BJZ.dll置于V_DY2项目文件夹下

[DY2.cpp]

#include<iostream>
#include<wtypes.h>
#include "framework.h"
//引用V_BJZ项目中的头文件
#pragma comment(lib,"G:\\Cplus_workspace\\V_1\\V_DY2\\V_BJZ.lib") 
//将V_BJZ.lib库文件连接到目标文件中(即本工程)
using namespace std;

int main()
{     
    int a, b, sum;
    cin >> a >> b;
    sum=ReturnSum(a, b);    
    cout<<"sum = "<<sum<<endl;     
    return 0;
} 

【效果图】

【遇到的问题】

1、程序中使用的文件路径建议使用双斜杠。单斜杠会提示语法错

2、静态加载方式不仅要把文件放到项目文件夹下,还要在VS上导入一下(VS2019快捷键为Shift Alt A),否则提示语法错

3、静态加载方式EXE单独执行时需将调用的DLL文件放在同目录下,否则报错

4、头文件不需要的不建议写,会报出稀奇古怪的错误

5、静态加载方式将导入声明写上了反而报错,去掉就没问题了

猜你喜欢

转载自www.cnblogs.com/liqing45/p/11749882.html