You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++扩展HDF5一维数据集写入异常问题求助

问题:HDF5数据集扩展写入异常

我尝试在HDF5文件中创建可扩展数据集,参考官方demo编写了测试代码,但扩展部分写入异常。原数据[1,2,3,4]正常写入,但预期写入的扩展数据[99,98,97,96,95,94]实际写入错误,表现为从数组0位置开始写入且剩余单元格为无效值。目前用了一个不规范的临时写法解决,但怀疑是H5Sselect_hyperslab的使用问题,求正确解决方法。

测试代码如下:

#include <H5Cpp.h>
#include <hdf5.h>

using namespace H5;    
int main(int argc, char* argv[]) {
  const int DIM0 = 4;
  const int EDIM0 = 6;
  const int CHUNK0 = 1;
  const std::string FILE = "/tmp/test.h5";
  const std::string DATASET = "DS1";

  hid_t file, space, dset, dcpl; /* Handles */
  herr_t status;
  hsize_t dims[1] = {DIM0};
  hsize_t extdims[1] = {EDIM0 + DIM0};
  hsize_t maxdims[1];
  hsize_t chunk[1] = {CHUNK0};
  hsize_t start[1];
  hsize_t count[1];
  int wdata[DIM0];
  int wdata2[EDIM0];

  /*
   * Fill Dataset
   */
  for (int i = 0; i < DIM0; i++)
    wdata[i] = i + 1;

  file = H5Fcreate(FILE.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

  maxdims[0] = H5S_UNLIMITED;
  space = H5Screate_simple(1, dims, maxdims);
  dcpl = H5Pcreate(H5P_DATASET_CREATE);
  status = H5Pset_chunk(dcpl, 1, chunk);

  dset = H5Dcreate(file, DATASET.c_str(), H5T_STD_I32LE, space, H5P_DEFAULT, dcpl, H5P_DEFAULT);

  status = H5Dwrite(dset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &wdata[0]);

  /*
   * Extend the dataset.
   */
  status = H5Dset_extent(dset, extdims);
  space = H5Dget_space(dset);
  for (int i = 0; i < EDIM0; i++)
    wdata2[i] = 100 - (i + 1);

  status = H5Sselect_all(space);

  /*
   * Subtract a hyperslab reflecting the original dimensions from the
   * selection.  The selection now contains only the newly extended
   * portions of the dataset.
   */
  start[0] = DIM0;
  count[0] = EDIM0;
  status = H5Sselect_hyperslab(space, H5S_SELECT_SET, start, NULL, count, NULL);

  status = H5Dwrite(dset, H5T_NATIVE_INT, H5S_ALL, space, H5P_DEFAULT, &wdata2[0]);

  status = H5Dclose(dset);
  status = H5Sclose(space);
  status = H5Fclose(file);
}

临时hack写法:

status = H5Dwrite(dset, H5T_NATIVE_INT, H5S_ALL, space, H5P_DEFAULT, &wdata2[0]-DIM0);

内容的提问来源于stack exchange,提问作者Mr Squid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:20:53