1
問題描述:dll的路徑必須在靜態常量(const),所以是無法通過一般方法把c:\\FirstDll.dll作為變數傳入的.
下面介紹的方法鑒於:http://www.cnblogs.com/wuwei2150/archive/2008/07/15/1228346.html
但原處有小處錯誤,餘在此修改,並最佳化.
[DllImport("c:\\FirstDll.dll", EntryPoint="Add")]
public static extern int Add(int a,int b);
#region 編碼資訊
/*
* 開發人員:秦仕川
* Date: 2010-6-9
* Time: 15:57
* 修改人員:秦仕川
* 修改時間:
*/
#endregion
using System;
using QSMY.DynamicLoadDLLFile;
using System.Runtime.InteropServices;
namespace TestDLL
{
class Program
{
delegate int AddDelegate(int a,int b);
public static void Main(string[] args)
{
AddDelegate addHandler;
DllDotNetHelper helper=new DllDotNetHelper();
helper.LoadLibrary("c:\\FirstDll.dll");//這裡就可以動態載入了
addHandler= (AddDelegate)helper.GetFunctionDelegateObject("Add",typeof(AddDelegate));
int c=addHandler(4553,35665);
Console.WriteLine(c);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
1 #region 編碼資訊
2 /*
3 * 開發人員:秦仕川
4 * Date: 2010-6-9
5 * Time: 15:59
6 * 修改人員:秦仕川
7 * 修改時間:
8 */
9 #endregion
10 using System;
11 using System.Collections.Generic;
12 using System.Runtime.InteropServices;
13
14 namespace QSMY.DynamicLoadDLLFile
15 {
16 public class DllDotNetHelper
17 {
18 private IntPtr _dllPtr=IntPtr.Zero;
19 public void LoadLibrary(string dllFileFullName){
20 _dllPtr= LibrayHelper.LoadLibrary(dllFileFullName);
21 }
22 public void FreeLibary(){
23 if (_dllPtr!=IntPtr.Zero) {
24 LibrayHelper.FreeLibrary(_dllPtr);
25 }
26 }
27 /// <summary>
28 /// 擷取該方法的委託Object對象
29 /// </summary>
30 /// <param name="functionName">函數名</param>
31 /// <param name="t">該方法的委託類型</param>
32 /// <returns></returns>
33 public object GetFunctionDelegateObject(string functionName,Type t)
34 {
35 int addr = LibrayHelper.GetProcAddress(_dllPtr, functionName);
36 if (addr == 0)
37 return null;
38 else
39 return Marshal.GetDelegateForFunctionPointer(new IntPtr(addr), t);
40 }
41
42 }
43 }
44