项目背景
目前在项目中用到了_findfirst方法来获取文件夹中的文件列表,使用_findfirst来获取文件句柄,在32位系统下可以正常运行,但是迁移到64位系统下,获取文件列表的函数直接崩溃。
问题的原因
经过查看_findfirst源码发现,_findfirst宏定义实际上是函数_findfirst64i32()的宏定义_findfirst64i32()函数原型:
intptr_t _findfirst64i32(
_In_ char const* _FileName,
_Out_ struct _finddata64i32_t* _FileData
);
这个我们发现,该函数的返回值实际上是intptr_t类型,从这个发现了问题所在。原来在代码中获取_findfirst64i32返回值时只用了long类型来接受。而intptr_t类型在不同的平台上定义了不同类型的值,如果在64位系统上使用long类型来接受intptr_t的值会发生数据“分割”,导致文件句柄的值发生变化(相当于指针指向了一个未知的区域),对这个指针的任何操作都会发生崩溃。
#define _WIN64
typedef __int64 intptr_t;
#else
typedef int intptr_t;
解决方案
- 将_findfrist函数的返回值类型定义成intptr_t
- 在不同的平台上使用不同的指针类型