C#调用c++dll另外一种方式

By admin at 2022-05-07 • 0人收藏 • 491人看过
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace easyPr32
{
    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;
        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);
        }
    }
}

使用:

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

namespace easyPr32
{
    public class Class1
    {

    public delegate int do_lps_func(string file_name, int show_type);
    public delegate IntPtr get_license_str_func();
    public delegate IntPtr get_color_str_func();
       
        public static string loadPic(string path)
        {
            DllInvoke dll = new DllInvoke(@"C:\Users\Desktop\CreateDLL.dll");
            do_lps_func lps = (do_lps_func)dll.Invoke("do_lps", typeof(do_lps_func));
            get_license_str_func get_license = (get_license_str_func)dll.Invoke("get_license_str", typeof(get_license_str_func));
            get_color_str_func get_color = (get_color_str_func)dll.Invoke("get_color_str", typeof(get_color_str_func));

            int result_num = lps(path, 2);// 只写结果
            if (result_num == 0)
            {
                IntPtr license = get_license();
                string license_str = Marshal.PtrToStringAnsi(license);
                IntPtr color = get_color();
                string color_str = Marshal.PtrToStringAnsi(color);
                string color_CHN;
                if (color_str == "BLUE")
                    color_CHN = "蓝牌:";
                else if (color_str == "YELLOW")
                    color_CHN = "黄牌:";
                else if (color_str == "GREEN")
                    color_CHN = "绿牌:";
                else
                    color_CHN = "未知:";
                return color_CHN + license_str;
            }
            return null;   
        }
    }
}

记录备用.

登录后方可回帖

登 录
信息栏
 私人小站

本站域名

ChengXu.XYZ

投诉联系:  popdes@126.com



快速上位机开发学习,本站主要记录了学习过程中遇到的问题和解决办法及上位机代码分享

这里主要专注于学习交流和经验分享.
纯私人站,当笔记本用的,学到哪写到哪.
如果侵权,联系 Popdes@126.com

友情链接
Aardio官方
Aardio资源网


才仁机械


网站地图SiteMap

Loading...