Unity中Mac(含M1)及Windows可用磁盘空间计算方案求助
全平台磁盘空间检测解决方案(适配M1 Mac)
一、替代第三方插件的跨平台工具
放弃原插件,改用原生支持多架构的成熟库,避免M1兼容问题:
Python环境:用
psutil,原生适配arm64,能精准过滤虚拟驱动器:import psutil def get_real_disk_space(): valid_disks = [] # 只遍历物理挂载的分区,跳过虚拟/临时文件系统 for partition in psutil.disk_partitions(all=False): if 'loop' not in partition.device and 'tmpfs' not in partition.fstype: usage = psutil.disk_usage(partition.mountpoint) valid_disks.append({ "设备路径": partition.device, "挂载点": partition.mountpoint, "总容量(GB)": usage.total // (1024**3), "可用空间(GB)": usage.free // (1024**3), "已用空间(GB)": usage.used // (1024**3) }) return valid_disks直接用
pip install psutil安装,M1 Mac无需额外编译。Node.js/Electron环境:用
diskusage,预编译了arm64版本,支持过滤虚拟分区:const diskusage = require('diskusage'); const os = require('os'); async function getRealDiskSpace() { // Mac优先取根目录,其他系统取用户目录挂载点 const targetMount = os.platform() === 'darwin' ? '/' : os.userInfo().homedir.split('/')[1]; const diskData = await diskusage.check(targetMount); // Mac下过滤/Volumes里的虚拟镜像、网络驱动器 if (os.platform() === 'darwin') { if (!diskData.mountpoint.includes('/Volumes/') || diskData.mountpoint === '/') { return { 总容量(GB): diskData.total / (1024**3), 可用空间(GB): diskData.free / (1024**3), 已用空间(GB): (diskData.total - diskData.free) / (1024**3) }; } } return diskData; }用
npm install diskusage安装即可,M1 Mac直接用预编译包。
二、修复自定义Objective-C库的M1兼容问题
如果一定要自己写OC库,解决编译和符号问题:
- 编译通用架构二进制:
在Xcode里选Target → Build Settings → Architectures,设为Standard Architectures (Apple Silicon, Intel);或者命令行编译:clang -arch arm64 -arch x86_64 -framework Foundation -o diskutils diskutils.m - 导出C兼容接口,避免调用混淆:
#import <Foundation/Foundation.h> extern "C" { // 获取指定挂载点的可用空间(字节) uint64_t get_free_disk_space(const char* mount_point) { NSURL* url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:mount_point]]; NSError* error; NSDictionary* attrs = [url resourceValuesForKeys:@[NSURLVolumeAvailableCapacityKey] error:&error]; return error ? 0 : [attrs[NSURLVolumeAvailableCapacityKey] unsignedLongLongValue]; } }
三、通用虚拟驱动器过滤规则
不管用哪种方案,按以下规则过滤非物理磁盘:
- MacOS:只保留
/根目录和物理分区,排除/Volumes下的镜像、网络驱动器,跳过tmpfs、devfs格式。 - Windows:只保留固定磁盘(DriveType=3),排除A:/Z:/等虚拟盘符。
- Linux:跳过
loop、tmpfs、sysfs等挂载点,只保留ext4/xfs等物理磁盘格式。
内容的提问来源于stack exchange,提问作者Gevorg Chobanyan
相关产品推荐
相关产品推荐

