C语言编写dll并调用
dll.h文件
1 #ifndef _DLL_H_
2 #define _DLL_H_
3
4 #if BUILDING_DLL
5 #define DLLIMPORT __declspec(dllexport)
6 #else
7 #define DLLIMPORT __declspec(dllimport)
8 #endif
9
10 DLLIMPORT int add(int i,int j);
11
12 #endif
dll.c文件
1 /* Replace "dll.h" with the name of your header */
2 #include "dll.h"
3 #include <windows.h>
4
5 DLLIMPORT int add(int i, int j)
6 {
7 return i+j;
8 }
9
10 BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)
11 {
12 switch(fdwReason)
13 {
14 case DLL_PROCESS_ATTACH:
15 {
16 break;
17 }
18 case DLL_PROCESS_DETACH:
19 {
20 break;
21 }
22 case DLL_THREAD_ATTACH:
23 {
24 break;
25 }
26 case DLL_THREAD_DETACH:
27 {
28 break;
29 }
30 }
31
32 /* Return TRUE on success, FALSE on failure */
33 return TRUE;
34 }
exe.c文件(调用dll的)
1 #include <windows.h>
2 #include <stdio.h>
3
4 typedef int (*Fun)(int,int); //这里声明一个函数指针,typedef 关键字是必须的,好像要显示调用dll中的函数,都需要这样用函数指针给出声明
5
6 int main()
7 {
8 HINSTANCE hDll;
9 Fun Add;
10 hDll=LoadLibrary("myDll.dll");
11 if (hDll==NULL)
12 {
13 printf("%s","failed to load dll!\n");
14 }
15 else
16 {
17 printf("%s","succeeded in loading dll\n");
18 Add=(Fun)GetProcAddress(hDll,"add");
19 if (Add!=NULL)
20 {
21 int i,j;
22 printf("%s","input the first number:");
23 scanf("%d",&i);
24 printf("%s","input the first number:");
25 scanf("%d",&j);
26 printf("sum = %d\n",Add(i,j));
27 }
28 }
29 FreeLibrary(hDll);
30
31 system("pause");
32 return 0;
33 }
本文来自博客园,作者:FSOLRE,转载请注明原文链接:https://www.cnblogs.com/VMxxxz/p/14269272.html