请问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();
        }
    }
}

一个方法是安装程序里根据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;
        }

图片说明添加宏定义 这样来区分

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_DLLVersion64();
        [DllImport(@"D:\demo\串口Demo\Demo1\Demo1\x86\ComMon.dll")]
        private static extern int CM_DLLVersion32();

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

if (Environment.Is64BitOperatingSystem)
CM_DLLVersion64();;
else
CM_DLLVersion32();