.NET动态载入c++动态链接库

 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 



少侠,我看你气度不凡天赋异禀,这么帅,来了就给推荐一把吧




我的最近更新
最新发布文章、框架、咨询等,来看看吧
原文地址:https://www.cnblogs.com/humble/p/1754913.html