您的位置:首页 > 编程语言 > C#

C# api 动态加载C++的DLL函数方法

2010-08-12 09:31 239 查看
C++函数如下:

// testdll3.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"

BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}

extern "C" __declspec(dllexport) int add(int * a,int * b)
{
return *a + *b;
}

C#中动态加载方法:

首先写一个加载DLL文件的类:

#region Win API 声明
class LoadDllAPI
{

[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);
}
#endregion

public class LoadDll
{
IntPtr DllLib;//DLL文件名柄
#region 构造函数
public LoadDll()
{ }
public LoadDll(string dllpath)
{
DllLib = LoadDllAPI.LoadLibrary(dllpath);
}
#endregion
/// <summary>
/// 析构函数
/// </summary>
~LoadDll()
{
LoadDllAPI.FreeLibrary(DllLib);//释放名柄
}
public void initPath(string dllpath)
{
if (DllLib == IntPtr.Zero)
{
DllLib = LoadDllAPI.LoadLibrary(dllpath);
}
}
/// <summary>
/// 获取DLL中一个方法的委托
/// </summary>
/// <param name="methodname"></param>
/// <param name="methodtype"></param>
/// <returns></returns>
public Delegate InvokeMethod(string methodname, Type methodtype)
{
IntPtr MethodPtr = LoadDllAPI.GetProcAddress(DllLib, methodname);

return (Delegate)Marshal.GetDelegateForFunctionPointer(MethodPtr, methodtype);
}
}


以上方法编译.

调用:

*  loadDLL.LoadDll loaddll = new loadDLL.LoadDll();//实例化加载DLL文件的类,,如上
*         public delegate int delegateadd(IntPtr a,IntPtr b);//声明此方法的一个委托

//一个调用用的按钮
private void button1_Click(object sender, EventArgs e)
{
loaddll.initPath("testdll3.dll");//载入文件
delegateadd m = (delegateadd)loaddll.InvokeMethod("add", typeof(add));//获取其中方法的委托
int a=1;int b=2;

int re = m(out a, out b);//得到RE=3,,成功
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: