我想将 STL 容器中包含的数据写入 HDF5 文件。根据我收集的信息,我需要声明一个连续的内存块,并使用 "hdf5.h"
C API 将数据从内存缓冲区传输到磁盘。
对于常规数据空间,过程很简单;只需要使用new
在堆栈上创建临时数组。 HDF5“理解”这种内存布局。
当处理不规则数据空间时,情况就不同了,因为必须使用专用类型 hvl_t
。
以下代码片段可以工作,但不是 ISO C++(11):
// Test data
std::vector< std::vector<int> > jagged_array(3);
jagged_array[0] = {0};
jagged_array[1] = {0, 1, 2, 3};
jagged_array[2] = {0, 1, 2};
hvl_t X[jagged_array.size()];
for (unsigned int i = 0; i < jagged_array.size(); ++i) {
X[i].len = jagged_array[i].size();
int * ptr = (int *) malloc (X[i].len * sizeof(int));
for (unsigned int j = 0; j < X[i].len; ++j) {
ptr[j] = jagged_array[i][j];
}
X[i].p = (void *) ptr;
}
我的C非常生锈了;除了非法行 hvl_t X[jagged_array.size()];
之外,此代码片段几乎完全从 HDF5 示例页面中抄袭。
我应该如何声明一个在运行时确定大小的 hvl_t
?
它肯定涉及 malloc
,但我真的被难住了。
最佳答案
我知道已经有一段时间了,但我今天才发现这个。这是一个正确的 C++ 解决方案,不分配额外的内存,而只是将指向 vector 的指针存储在 vlen_t
中:
// Test data
std::vector< std::vector<int> > jagged_array(3);
jagged_array[0] = {0};
jagged_array[1] = {0, 1, 2, 3};
jagged_array[2] = {0, 1, 2};
hvl_t X[jagged_array.size()];
for (unsigned int i = 0; i < jagged_array.size(); ++i) {
X[i].len = jagged_array[i].size();
X[i].p = (void*) &jagged_array[i].front();
}
关于c - HDF5 可变长度结构,可变长度(C API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29131758/