VS2019 调用C/C++的DLL

参考文章一:System.DllNotFoundException,无法加载 DLL“****.dll”_5436649486的博客-CSDN博客_system.dllnotfoundexception参考文章二:

C# 尝试读取或写入受保护的内存,这通常指示其他内存已损坏。常见解决办法_sweet_infancy的博客-CSDN博客_尝试读取或写入受保护的内存。这通常指示其他内存已损坏。

加载DLL错误

根据文章一,要注意平台跟调用的DLL的位数对应,32位对32位,x64对x64

找不到DLL错误

要把DLL放在Debug文件夹中,注意x64平台要放在x64文件夹中的Debug文件夹

调用DLL错误

一般的参数直接传入即可,有些指针参数,需要转换成指针传入DLL中,这里直接贴源码

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*引入C/C++生成的dll时需要添加*/
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    class Program
    {
        //引入DLL 在debug文件下
        [DllImport("CN200WLDll.dll", EntryPoint = "uds_calc_key", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr uds_calc_key(IntPtr par1, IntPtr b); //DLL 中函数入口名,参数类型,这里是指针类型
        static void Main(string[] args)
        {
            IntPtr b = Marshal.StringToHGlobalAnsi("");  // 传入指针 空参数1 
            IntPtr ptrIn = Marshal.StringToHGlobalAnsi("1CAF1408");  //指针 string类型参数
            IntPtr ptrRet = uds_calc_key(ptrIn, b);      //将指针参数传入DLL, 返回指针类型

            string temp = Marshal.PtrToStringAnsi(ptrRet);   //指针类型转换string

            Console.WriteLine(temp);
            Console.ReadKey();

        }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值