C#-引用第三方動態庫文件(C++)DLL使用方法

     1.編寫一個類文件在使用加載DLL文件的方法,這樣做的話,可以將第三方庫和本項目的dll分開存放不同的文件夾,管理程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace test_interface{
    public class DllInvoke
    {
        #region Win API
        [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);
        #endregion

        private IntPtr hLib; 
        //dll文件的路徑
        public DllInvoke(String DLLPath)
        {
            hLib = LoadLibrary(DLLPath);
        }

        ~DllInvoke()
        {
            FreeLibrary(hLib);            
        }

        //将要执行的函数转换为委托
        public Delegate Invoke (string APIName,Type t)  
        {
            IntPtr api = GetProcAddress(hLib, APIName);
            return (Delegate)Marshal.GetDelegateForFunctionPointer(api, t);
        }
    }
    
}

 

2.在form代碼上配置dll的物理路徑,為了方便管理開發的程序,將第三方庫單獨存放一個目錄,如lib目錄中在( exe文件運行根目錄下)

// 获取和设置包括该应用程序的目录的名称。
//System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase:如果在VS調試中,路徑為debug的路徑System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase:如果運行中(客戶環境中),路徑為exe文件根目錄的路徑


sFilePath =(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "lib\\CreateDLL.dll");
DllInvoke dll = new DllInvoke(sFilePath);

do_lps_func lps = (do_lps_func)dll.Invoke("do_lps", typeof(do_lps_func));

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值