windows制作动态链接库和使用一

制作:

//myDll.h
_declspec(dllexport) int add(int a,int b);
_declspec(dllexport) int sub(int a,int b);
//myDll.cpp
#include"myDll.h"//这个必须有,不然导不出去,可以不要头文件,重点_declspec(dllexport)
int add(int a,int b)
{
return a+b;
}

int sub(int a,int b)
{
  return a-b;  
}
//入口函数,文件名随意xx.cpp
#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;
}

使用:

1,typedef函数指针;

2,声明指针变量;

3,动态加载dll到内存;

4,获取函数地址;

5,调用函数;

6,释放动态链接库,FreeLibary(HMODULE hDll);

//test.cpp
#include<stdio.h>

typedef int (*LPdd)(int,int);
typedef int (*LPsub)(int,int);

LPadd add;
LPsub sub;
int main()
{
    HMODULE hDll = LoadLibary("demoDll.dll");
   
   add = (LPadd)GetPrecAddress(hDll,"add");
   sub = (LPsub)GetProcAddress(hDll,"sub");

   int x=add(10,2);//x=12
  int y=sub(10,2);//y=8

return 0;        
}
posted @ 2020-01-19 19:24  AGB  阅读(230)  评论(0编辑  收藏  举报