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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM