当前位置:   article > 正文

c语言调用dll动态库 -- 仅仅使用dll文件_只有dll文件可以调用吗

只有dll文件可以调用吗

1、动态库生成:

新建.cpp

  1. #include <windows.h>
  2. #include "CalSeedKey.h"
  3. DLL_API int _key = 255;
  4. DLL_API int seedkey = 0;
  5. DLL_API int CalSeedKey1(int seed)
  6. {
  7. seedkey = seed-1;
  8. return 0;
  9. }
  10. DLL_API int CalSeedKey2(int seed,int key)
  11. {
  12. return seed+key;
  13. }
  14. DLL_API int CalSeedKey3(int seed, int key)
  15. {
  16. key = seed + key;
  17. return 0;
  18. }

新建.h

  1. #ifdef DLL_EXPORTS
  2. #define DLL_API __declspec(dllexport)
  3. #else
  4. #define DLL_API __declspec(dllimport)
  5. #endif
  6. extern DLL_API int seedkey;
  7. extern DLL_API int _key;
  8. DLL_API int CalSeedKey1(int seed);
  9. DLL_API int CalSeedKey2(int seed ,int key);
  10. DLL_API int CalSeedKey3(int seed ,int key);

新建入口函数dllmain.cpp:

  1. #include <windows.h>
  2. BOOL APIENTRY DllMain( HMODULE hModule,
  3. DWORD ul_reason_for_call,
  4. LPVOID lpReserved
  5. )
  6. {
  7. switch (ul_reason_for_call)
  8. {
  9. case DLL_PROCESS_ATTACH:
  10. case DLL_THREAD_ATTACH:
  11. case DLL_THREAD_DETACH:
  12. case DLL_PROCESS_DETACH:
  13. break;
  14. }
  15. return TRUE;
  16. }

新建CalSeedKey.def模块文件导出函数:

  1. LIBRARY
  2. EXPORTS
  3. seedkey @1
  4. _key @2
  5. CalSeedKey1 @3
  6. CalSeedKey2 @4
  7. CalSeedKey3 @5

生成dll:

2、dll加载调用

主要是指针函数的使用,通过dll导出函数的地址。

  1. typedef int(*CalseedKey)(int a);
  2. typedef int(*CalseedKey1)(int a,int b);
  3. typedef int(*_Key);

新建callDll.cpp:

  1. #include <stdio.h>
  2. #include <windows.h>
  3. int main()
  4. {
  5. int a = 10, b = 10;
  6. HMODULE hDll = LoadLibrary("DLL.dll");
  7. if (hDll != NULL)
  8. {
  9. CalseedKey seedKey = (CalseedKey) GetProcAddress(hDll, "CalSeedKey1");
  10. CalseedKey1 seedKey2 = (CalseedKey1)GetProcAddress(hDll, "CalSeedKey2");
  11. CalseedKey1 seedKey3 = (CalseedKey1)GetProcAddress(hDll, "CalSeedKey3");
  12. _Key seedkey = (_Key)GetProcAddress(hDll, "seedkey");
  13. seedKey(100);
  14. printf("\nCalSeedKey:%d", *seedkey);
  15. printf("\nCalSeedKeyReturn(%d,%d):%d",a,b, seedKey2(a, b));
  16. seedKey3(a, b);
  17. printf("\nCalSeedKeyReturn(%d,%d):%d",a,b, b);
  18. }
  19. return 0;
  20. }

测试:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/204292
推荐阅读
相关标签
  

闽ICP备14008679号