MySafeHandle .cs 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. using Microsoft.Win32.SafeHandles;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace MeterVision.FreeAi
  9. {
  10. public class MySafeHandle : SafeHandleZeroOrMinusOneIsInvalid
  11. {
  12. // 构造函数,调用基类构造函数,传入句柄和有效性标志
  13. public MySafeHandle(IntPtr handle) : base(true)
  14. {
  15. this.SetHandle(handle); // 使用 SafeHandle 的方法来设置句柄
  16. }
  17. // 实现基类的 ReleaseHandle 方法,释放非托管资源
  18. protected override bool ReleaseHandle()
  19. {
  20. // 释放句柄
  21. return FreeLibrary(handle); // 假设你的 DLL 是通过 FreeLibrary 卸载的
  22. }
  23. // P/Invoke 调用,用于卸载 DLL
  24. [DllImport("kernel32.dll", SetLastError = true)]
  25. private static extern bool FreeLibrary(IntPtr hModule);
  26. }
  27. //---------------------------------------------------------------------------
  28. }