C#调用c++dll另外一种方式
By
admin
at 2022-05-07 • 0人收藏 • 521人看过
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace easyPr32 { public class DllInvoke { #region Win API [DllImport("kernel32.dll")] private extern static IntPtr LoadLibrary(string path); [DllImport("kernel32.dll")] private extern static IntPtr GetProcAddress(IntPtr lib, string funcName); [DllImport("kernel32.dll")] private extern static bool FreeLibrary(IntPtr lib); #endregion private IntPtr hLib; public DllInvoke(String DLLPath) { hLib = LoadLibrary(DLLPath); } ~DllInvoke() { FreeLibrary(hLib); } //将要执行的函数转换为委托 public Delegate Invoke(string APIName, Type t) { IntPtr api = GetProcAddress(hLib, APIName); return (Delegate)Marshal.GetDelegateForFunctionPointer(api, t); } } }
使用:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace easyPr32 { public class Class1 { public delegate int do_lps_func(string file_name, int show_type); public delegate IntPtr get_license_str_func(); public delegate IntPtr get_color_str_func(); public static string loadPic(string path) { DllInvoke dll = new DllInvoke(@"C:\Users\Desktop\CreateDLL.dll"); do_lps_func lps = (do_lps_func)dll.Invoke("do_lps", typeof(do_lps_func)); get_license_str_func get_license = (get_license_str_func)dll.Invoke("get_license_str", typeof(get_license_str_func)); get_color_str_func get_color = (get_color_str_func)dll.Invoke("get_color_str", typeof(get_color_str_func)); int result_num = lps(path, 2);// 只写结果 if (result_num == 0) { IntPtr license = get_license(); string license_str = Marshal.PtrToStringAnsi(license); IntPtr color = get_color(); string color_str = Marshal.PtrToStringAnsi(color); string color_CHN; if (color_str == "BLUE") color_CHN = "蓝牌:"; else if (color_str == "YELLOW") color_CHN = "黄牌:"; else if (color_str == "GREEN") color_CHN = "绿牌:"; else color_CHN = "未知:"; return color_CHN + license_str; } return null; } } }
记录备用.
登录后方可回帖