using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Test
{
class DLLLoader
{
[DllImport("kernel32.dll")]
public extern static IntPtr LoadLibrary(string path);
[DllImport("kernel32.dll")]
public extern static IntPtr GetProcAddress(IntPtr lib, string funcName);
[DllImport("kernel32.dll")]
public extern static bool FreeLibrary(IntPtr lib);
[DllImport("kernel32.dll")]
public static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("user32", EntryPoint = "CallWindowProc")]
public static extern int CallWindowProc(IntPtr lpPrevWndFunc, int hwnd, int MSG, int wParam, int lParam);
IntPtr DllLib;//DLL文件名柄
#region 构造函数
public DLLLoader()
{ }
public DLLLoader(string dllpath)
{
DllLib = LoadLibrary(dllpath);
}
#endregion
///
/// 析构函数
///
~DLLLoader()
{
FreeLibrary(DllLib);//释放名柄
}
public void initPath(string dllpath)
{
if (DllLib == IntPtr.Zero)
{
DllLib = LoadLibrary(dllpath);
}
}
///
/// 获取DLL中一个方法的委托
///
///
///
///
public Delegate InvokeMethod(string methodname, Type methodtype)
{
IntPtr MethodPtr = GetProcAddress(DllLib, methodname);
return (Delegate)Marshal.GetDelegateForFunctionPointer(MethodPtr, methodtype);
}
}
}
************调用***************
DLLLoader loaddll = new DLLLoader("E:\\workspaces\\WpfApplication1\\Debug\\DLL.dll");//实例化加载DLL文件的类,,如上
public delegate int delegateadd(ref int a);//声明此方法的一个委托
public void testMethod()
{
int a = 1;
delegateadd m = (delegateadd)loaddll.InvokeMethod("add", typeof(delegateadd));//获取其中方法的委托
int re = m(ref a);//得到RE,成功
}
**************DLL**************
extern "C" __declspec(dllexport) int add(int & a);
int add(int & a)
{
a = 10;
return 20;
}
C#调用C++DLL–委托
最新推荐文章于 2023-10-13 18:58:59 发布