Fortran编写HDF5文件报错:类型不匹配问题排查
Fortran编写HDF5文件的类型错误排查
问题描述
尝试用Fortran编写HDF5文件时遇到类型相关错误,以下是示例代码及翻译后的报错信息,需排查不恰当的类型问题:
示例代码
program ex11 ! 宣言 use, intrinsic :: iso_fortran_env use HDF5 implicit none intrinsic max, min ! character(LEN=1), parameter :: dsetname_x = "x" ! dataset for splits character(LEN=19), parameter :: output_file_path = "../data/output.hdf5" integer, parameter :: ndims = 2 ! integer :: error integer(HID_T) :: file_id integer(HID_T) :: dspace integer(HID_T) :: dset_id_x double precision, dimension(3,3) :: data integer(8), dimension(2), parameter :: dims = (/3,3/) integer :: i, j call h5fcreate_f(output_file_path, H5F_ACC_TRUNC_F, file_id, error) do i = 1,3 do j = 1,3 data(i,j) = 1.0 end do end do call h5screate_simple_f(ndims, dims, dspace, error) call h5dcreate_f(file_id, dsetname_x, H5T_NATIVE_DOUBLE, dspace, dset_id_x, error) call h5fclose_f(file_id, error) end program ex11
报错信息(翻译后)
HDF5-DIAG: 在HDF5 (1.14.0)线程0中检测到错误: #000: H5D.c第186行H5Dcreate2(): 无法同步创建数据集 主要错误: 数据集 次要错误: 无法创建文件 #001: H5D.c第134行H5D__create_api_common(): 无法创建数据集 主要错误: 数据集 次要错误: 无法创建文件 #002: H5VLcallback.c第1876行H5VL_dataset_create(): 数据集创建失败 主要错误: 虚拟对象层 次要错误: 无法创建文件 #003: H5VLcallback.c第1841行H5VL__dataset_create(): 数据集创建失败 主要错误: 虚拟对象层 次要错误: 无法创建文件 #004: H5VLnative_dataset.c第255行H5VL__native_dataset_create(): 不是有效的数据类型ID 主要错误: 例程参数无效 次要错误: 类型不恰当
问题根源
报错核心提示“不是有效的数据类型ID”,问题出在两处:
- 未初始化HDF5库:Fortran调用HDF5接口前必须先执行
h5open_f()初始化库,否则H5T_NATIVE_DOUBLE等常量无法被正确识别为合法的HDF5类型ID,直接导致参数类型无效。 - 维度参数类型不匹配:
h5screate_simple_f要求维度参数使用HDF5模块定义的HSIZE_T类型,原代码用integer(8)虽在部分平台兼容,但严格来说类型不匹配会引发参数传递错误,间接导致后续接口调用失败。
修改后的代码
program ex11 use, intrinsic :: iso_fortran_env use HDF5 implicit none intrinsic max, min character(LEN=1), parameter :: dsetname_x = "x" ! dataset for splits character(LEN=19), parameter :: output_file_path = "../data/output.hdf5" integer, parameter :: ndims = 2 integer :: error integer(HID_T) :: file_id integer(HID_T) :: dspace integer(HID_T) :: dset_id_x double precision, dimension(3,3) :: data ! 使用HDF5标准的HSIZE_T类型定义维度数组 integer(HSIZE_T), dimension(2), parameter :: dims = (/3,3/) integer :: i, j ! 初始化HDF5库,这是Fortran调用HDF5的必要步骤 call h5open_f(error) if(error /= 0) stop "HDF5初始化失败" call h5fcreate_f(output_file_path, H5F_ACC_TRUNC_F, file_id, error) if(error /= 0) stop "HDF5文件创建失败" do i = 1,3 do j = 1,3 data(i,j) = 1.0 end do end do call h5screate_simple_f(ndims, dims, dspace, error) if(error /= 0) stop "数据空间创建失败" call h5dcreate_f(file_id, dsetname_x, H5T_NATIVE_DOUBLE, dspace, dset_id_x, error) if(error /= 0) stop "数据集创建失败" ! 补充原代码遗漏的数据写入步骤 call h5dwrite_f(dset_id_x, H5T_NATIVE_DOUBLE, data, dims, error) if(error /= 0) stop "数据写入失败" ! 按逆序关闭资源:数据集 -> 数据空间 -> 文件,避免泄漏 call h5dclose_f(dset_id_x, error) call h5sclose_f(dspace, error) call h5fclose_f(file_id, error) ! 关闭HDF5库 call h5close_f(error) end program ex11
额外说明
- 原代码遗漏了数据写入步骤,即使创建数据集也不会有内容保存,修改后的代码补充了
h5dwrite_f调用。 - 资源关闭必须遵循逆序原则:先关闭数据集,再关闭数据空间,最后关闭文件,避免资源泄漏。
内容的提问来源于stack exchange,提问作者池田直哉
相关产品推荐
相关产品推荐

