‘dll的封装与调用方法’

方法一:适合封装类,使用时比较方便,但必须同时含有lib和dll文件,比较麻烦的是得提供头文件

代码

my.h


#pragma once
#ifndef __MY_H__
#define __MY_H__

#ifndef DLL_DLLEXPT
#define DLL_DLLEXPT  __declspec(dllexport)
#endif

#endif

mydll.h


#pragma once
#ifndef __MYDLL_H__
#define __MYDDL_H__

#include "my.h"
class DLL_DLLEXPT A

{
private:
int a;
int b;
public:
A(int a = 0, int b = 0);
~A();
int add(int a, int b);
int sub(int a, int b);
};
#endif

mydll.cpp


#include "mydll.h"

#ifndef MYDLL_DLLEXPT
#define MTDLL_DLLEXPT  __declspec(dllexport)
#endif

A::A(int a, int b):a(a), b(b) {};

A::~A() {};

int A::add(int a, int b) {
return a + b;
}

int A::sub(int a, int b) {
return a - b;
}

main.cpp —调用方法


#include "../Project1/mydll.h"
#include <iostream>
using namespace std;

#pragma comment (lib,"Project1.lib")

int main() {
A a;
int b = a.add(9, 9);
int c = a.sub(9, 8);
cout << b << endl;
cout << c << endl;
return 0;
}

方法二:适合函数的封装,且只需要dll文件,不能封装类

代码

mydll.cpp


extern "C"
_declspec(dllexport)int add(int a, int b) {
return a + b;
}
extern "C"
_declspec(dllexport)int sub(int a, int b) {
return a - b;
}

main.cpp


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

int main() {
HINSTANCE mydll = LoadLibrary("Project1.dll");
if (mydll == NULL) {
return 0;
}
int(*add)(int, int) = (int(*)(int, int))GetProcAddress(mydll, "add");
if (add == NULL) {
return 0;
}
cout << add(1, 2) << endl;
return 0;
}