标签:func private form 界面 add npoi type load typeof
场景:
WPF界面调用C++动态库,由于库的名称不是固定的,因此没法用DllImport,想到了用windows api中的LoadLibrary,一番折腾后调用成功
关键代码:
[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); public Delegate Invoke(string APIName, Type t) { IntPtr api = GetProcAddress(hLib, APIName); return (Delegate)Marshal.GetDelegateForFunctionPointer(api, t); }
调用
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void GetMethod(StringBuilder hOut); DllInvoke dll = new DllInvoke(pluginFile.FullName); GetMethod getMethod = (GetMethod)dll.Invoke("GetMethod", typeof(GetMethod)); int nLen = 4096; StringBuilder result = new StringBuilder(nLen); getMethod(result,ref nLen);
注意:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]必须加上,否则会出现异常:
Additional information: 对 PInvoke 函数“***”的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。请检查 PInvoke 签名的调用约定和参数与非托管的目标签名是否匹配。
因为这句话没加,一开始以为数据封送问题,折腾了好久,记录一下
标签:func private form 界面 add npoi type load typeof
原文地址:https://www.cnblogs.com/dkhuang/p/14868226.html