c++动态库中回调函数使用

dll 源文件 add.cpp

View Code
 1 typedef int (*pfunc)(int, int);

 2 pfunc myadd;

 3 

 4 void __stdcall  add(pfunc add)

 5 {

 6     myadd = add;

 7 }

 8 

 9 int __stdcall  true_add(int x, int y)

10 {

11     return myadd(x, y);

12 }

def文件 add.def

View Code
1 EXPORTS

2 

3 add            @1

4 true_add            @2    

生成库add.lib add.dll

调用dll的文件 callback.cpp

View Code
 1 #include <iostream>

 2 #include <Windows.h>

 3 

 4 typedef int (*padd)(int, int);

 5 

 6 typedef void (CALLBACK *pfunc1)(padd);

 7 typedef int (CALLBACK *pfunc2)(int, int);

 8 

 9 int my_add(int a, int b)

10 {

11     return a + b ;

12 }

13 

14 

15 

16 int main(int argc, char* argv[])

17 {

18     HINSTANCE hDll = LoadLibrary("add.dll");

19     if (NULL == hDll)

20     {

21         std::cout << "load library add.dll failed" << std::endl;

22     }

23     pfunc1 pfAdd1 = (pfunc1)GetProcAddress(hDll, "add");

24     pfunc2 pfAdd2 = (pfunc2)GetProcAddress(hDll, "true_add");

25     pfAdd1(my_add);

26     int sum = pfAdd2(3, 5);

27     std::cout << sum << std::endl;

28 

29     return 0;

30 }

注:Vs编译dll时需要在Property/Linker/Input ->Module Definition File中加入add.def

你可能感兴趣的:(回调函数)