关于根据Build Platform或者OS 加载x86或者x64 dll的问题

本文介绍了如何根据不同系统环境加载SQLite.dll的方法,包括通过IntPtr.Size、WMI和Environment.Is64BitOperatingSystem判断操作系统位数,并提供了WPF程序中AppDomain加载DLL的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      最近编程遇到引用SQLite.dll的问题。SQLite.dll有两个版本,x86和x64,如果仅仅是自己的环境使用,那么添加对应版本的引用,那是完全没有问题的。但是一旦程序要发布出去,或者在不用的平台环境上使用,那么这么做就存在隐患了。最终就需要根据不同系统环境来加载dll。

      首先,是判断系统平台。

      1. IntPtr

      在build platform是Any CPU的情况,根据IntPtr.Size的值判断是x86还是x64。

 1    if (IntPtr.Size == 8)
 2             {
 3                 //x64
 4             }
 5             else if (IntPtr.Size == 4)
 6             {
 7                 //x86
 8             }
 9             else
10             {
11                 //other
12             }

      如果build platform是x86或者x64,那么IntPtr.Size就跟OS 平台没有关系,得到的大小是build platform对应的值。

      

      2.WMI

      这个方法是用OS接口的扩展方法,判断OS平台,完全不会受到build platform的影响。需要添加对System.Management.dll的引用。 

 1 SelectQuery query = new SelectQuery("select AddressWidth from Win32_Processor");
 2             ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
 3             ManagementObjectCollection moCollection = searcher.Get();
 4             foreach (ManagementObject mo in moCollection)
 5             {
 6                 foreach (PropertyData property in mo.Properties)
 7                 {
 8                     if (property.Name.Equals("AddressWidth"))
 9                     {
10                         UInt16 i =  Convert.ToUInt16(property.Value);
11                     }
12                 }
13             } 

  

      3.Environment.Is64BitOperatingSystem

      如果你的程序的.Net Framework版本是4.0及以上的话,可以直接使用这个属性判断OS版本

 

      判断完OS版本之后,是加载dll.

      由于我的是WPF程序,使用AppDomain的事件方法加载。   

 1         public MainWindow()
 2         {
 3             AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => CurrentDomain_AssemblyResolve();
 4             InitializeComponent();           
 5         }
 6 
 7         private System.Reflection.Assembly CurrentDomain_AssemblyResolve()
 8         {
 9             Assembly loadedAssembly = null;
10             if (IntPtr.Size == 8)
11             {
12                 loadedAssembly = Assembly.LoadFile("***");
13             }
14             else if (IntPtr.Size == 4)
15             {
16                 loadedAssembly = Assembly.LoadFile("***");
17             }
18             else
19             {
20                 //
21             }
22             return loadedAssembly;
23         }

 

     

转载于:https://www.cnblogs.com/ByronsHome/p/3771061.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值