C# 动态调用非托管DLL 作者: juoliii 时间: 2023-05-07 分类: 开发,c# 评论 **1.首先从系统DLL导入3个函数** ``` [DllImport("kernel32.dll", EntryPoint = "LoadLibraryA")] static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName); [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")] static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName); [DllImport("kernel32.dll", EntryPoint = "FreeLibrary")] static extern bool FreeLibrary(IntPtr hModule); ``` **2.申明一个需要调用的DLL中函数的委托** ``` public delegate int SayHello(String str); ``` **3.载入DLL并且动态调用DLL中的函数** 载入DLL并且获取函数地址,通过委托方式动态调用 ``` IntPtr hModule = LoadLibrary(@"ylgjdrg.dll"); IntPtr intPtr = GetProcAddress(hModule, "SayHello"); SayHello sayHello= (SayHello)System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(intPtr, typeof(SayHello)); sayHello("测试"); ``` **4.从内存释放DLL** 调用程序关闭之前释放DLL ``` FreeLibrary(hModule) ```