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

请问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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题