2024年4月30日发(作者:)

.

关于C#动态调用Dll的开发方法

前段时间做了一个项目,其中要求调用一个VC6开发的Dll文件,而该文件有多个不同

的版本,所以要支持动态调用,并支持卸载。

在收集了一些这方面的资料后,编写了下面的类,该类可以方便的调用各种类型的dll,

而且简单实用。

[c-sharp] view plaincopy

1. using System;

2. using c;

3. using ;

4. using pServices;

5.

6. namespace testdll

7. {

8. ///

9. ///

10. ///

11. class InvokeDll

12. {

13. #region Win API

14. [DllImport("")]

15. private extern static IntPtr LoadLibrary(string path);

16.

17. [DllImport("")]

18. private extern static IntPtr GetProcAddress(IntPtr lib, string funcN

ame);

19.

20. [DllImport("")]

21. private extern static bool FreeLibrary(IntPtr lib);

22. #endregion

23.

24. private IntPtr hLib;

25. public InvokeDll(String DLLPath)

26. {

27. hLib = LoadLibrary(DLLPath);

28. }

29.

30. ~InvokeDll()

.;

.

31. {

32. FreeLibrary(hLib);

33. }

34.

35. //将要执行的函数转换为委托

36. public Delegate Invoke (string APIName,Type t)

37. {

38. IntPtr api = GetProcAddress(hLib, APIName);

39. if (api == )

40. return null;

41. else

42. return egateForFunctionPointer(api, t);

43. }

44. }

45.

46. }

使用时,先根据dll中的命令写出相关的代理

public delegate int MsgBox(int hwnd,string msg,string cpp,int ok);

public delegate int DeleteFile(string msg);

然后按下面的代码做就可以了。

[c-sharp] view plaincopy

1. InvokeDll dll = new InvokeDll("");

2. MsgBox mymsg = (MsgBox)("MessageBoxA", typeof(MsgBox));

3. mymsg(32(), "txtmsg", "titleText", 64);

4.

5.

6. InvokeDll dll1 = new InvokeDll("");

7. DeleteFile df= (DeleteFile)("DeleteFileA", typeof(DeleteFile));

8. df(deletedfilename);

.;