I have problems when I write a struct with arrays in it into an HDF5 dataset. Firstly, the window form doesn't start with the line:
H5T.insert(typeStruct, "string", 0, H5T.create_array(new H5DataTypeId(H5T.H5Type.C_S1), dims2));
The window form at least starts without the line, so I think there's something wrong with defining the compound datatype. I've looked into manuals and many examples, but I can't still fix the problems. Could I get an example of using compound datatypes to write a struct with multiple arrays in C#?
using HDF5DotNet;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
namespace WindowsFormsApplication1
{
public unsafe partial class Form1 : Form
{
public unsafe struct struct_TR
{
public string[] arr_currentLong;
public struct_TR(byte size_currentTime)
{
arr_currentLong = new string[size_currentTime];
}
}
public Form1()
{
InitializeComponent();
long ARRAY_SIZE = 255;
struct_TR structMade = new struct_TR(255);
for (int i = 0; i < 255; i++)
{
structMade.arr_currentLong[i] = i.ToString();
}
string currentPath = Path.GetDirectoryName(Application.ExecutablePath);
Directory.SetCurrentDirectory(currentPath);
H5FileId fileId = H5F.create(@"weights.h5", H5F.CreateMode.ACC_TRUNC);
long[] dims1 = { 1 };
long[] dims2 = { 1, ARRAY_SIZE };
H5DataSpaceId myDataSpace = H5S.create_simple(1, dims1);
H5DataTypeId string_type = H5T.copy(H5T.H5Type.C_S1);
H5DataTypeId array_tid1 = H5T.create_array(string_type, dims2);
H5DataTypeId typeStruct = H5T.create(H5T.CreateClass.COMPOUND, Marshal.SizeOf(typeof(struct_TR)));
H5T.insert(typeStruct, "string", 0, H5T.create_array(new H5DataTypeId(H5T.H5Type.C_S1), dims2));
H5DataSetId myDataSet = H5D.create(fileId, "/dset", typeStruct, myDataSpace);
H5D.writeScalar<struct_TR>(myDataSet, typeStruct, ref structMade);
}
}
}
the only way I know how to save structs with arrays is to create an array that is constant So for example this is a struct with an array of length 4.
Here an array of 4 structs containing an array is created:
The following lines of code write an array of structs to a HDF5 file:
The WriteCompounds method looks like this:
Three additional help functions are needed, two are shown here:
I also have a ReadCompounds to read the hdf5 file. The Hdf5.GetCompoundInfo method used in the CreateType method is also very long. So I won't show these methods here.
So that's quite a lot of code just for writing some structs. I have made a library called HDF5DotnetTools that allows you to read and write classes and structs much more easily. There you can also find the ReadCompounds and GetCompoundInfo methods.
In the unit tests of the HDF5DotnetTools you can also find examples of how to write classes with arrays