using Microsoft.Win32.SafeHandles; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace MeterVision.FreeAi { public class MySafeHandle : SafeHandleZeroOrMinusOneIsInvalid { // 构造函数,调用基类构造函数,传入句柄和有效性标志 public MySafeHandle(IntPtr handle) : base(true) { this.SetHandle(handle); // 使用 SafeHandle 的方法来设置句柄 } // 实现基类的 ReleaseHandle 方法,释放非托管资源 protected override bool ReleaseHandle() { // 释放句柄 return FreeLibrary(handle); // 假设你的 DLL 是通过 FreeLibrary 卸载的 } // P/Invoke 调用,用于卸载 DLL [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeLibrary(IntPtr hModule); } //--------------------------------------------------------------------------- }