99887744 2018-12-10 06:36 采纳率: 100%
浏览 1667
已采纳

请问C#如何自适应去调用C++ 32、64位Dll

由于32位64位dll名称一直,所有的函数也是一直的,这样的话如何区分以及调用呢?
图片说明

求指导。

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Demo1
{
    public partial class Form1 : Form
    {
        [DllImport(@"D:\demo\串口Demo\Demo1\Demo1\x64\ComMon.dll")]
        private static extern int CM_DLLVersion();
        [DllImport(@"D:\demo\串口Demo\Demo1\Demo1\x86\ComMon.dll")]
        private static extern int CM_DLLVersion();

        public Form1()
        {
            InitializeComponent();
        }
    }
}

  • 写回答

3条回答 默认 最新

  • 蒋晟 2018-12-13 17:20
    关注

    一个方法是安装程序里根据CPU类型决定装32位还是64位版本,这样你代码里只要写DllImport ComMon.dll,CLR到应用程序目录下加载到的就是正确的版本。

    另一个方法是32位和64位版本的DLL都装上,但是装到不同目录,DllImport 的时候还是直接写ComMon.dll,但是加载的时候自定义AppDomain.CurrentDomain.AssemblyResolve的处理来更改DLL搜索路径。

    static void Main()
    {

            AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;
                        ……
    
    private static Assembly AssemblyResolve(object sender, ResolveEventArgs args)
            {
                if (args.Name.StartsWith("ComMon.dll"))
                {
                    string assemblyName = args.Name.Split(new[] { ',' }, 2)[0] + ".dll";
                    string archSpecificPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                                                           Environment.Is64BitProcess ? "x64" : "x86",
                                                           assemblyName);
    
                    return File.Exists(archSpecificPath)
                               ? Assembly.LoadFile(archSpecificPath)
                               : null;
                }
    
                return null;
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料