Search code examples
typesdatasethdf5

Get the C++ data type found in HDF5 dataset


Wondering how to get HDF5 dataset values interpreted as standard and/or primitive C++ data types?

I have a .mat file that holds some user setting info. I'm not familiar with Matlab (.mat files) or HDF5. Some of that data would be doubles, booleans, strings or int types looking at the open file in Matlab.

I figured out how to read the file in using HDF5 and open a DataSet. I've also figured out how to iterate all the objects in the DataSet. But I just need to know what each type is so I can perform the appropriate read calls.

Below is the code I have so far that works.

H5::DataSet data_set;
    try
    {
        data_set = file->openDataSet("/USER_SETTINGS/OUTPUT_PATH");
    }
    catch (H5::LocationException e)
    {
        return false;
    }

    H5::DataSpace data_space = data_set.getSpace();
    H5::DataType data_type = data_set.getDataType();
    
    //Some other code not relevant to my question to read out rtnStringValue to an actual std::string

    data_set.read(rtnStringValue, data_type, data_space); //This call is specific to returning a string value.

I know to call the correct DataSet overload read function call because I know "OUTPUT_PATH" is a string.

My problem is what if I don't know what type the "/USER_SETTINGS/<some other thing>" contains? There is a different overload data_set.read function for other data types.


Solution

  • I believe I figured out what I am looking for. Got some answers from here, and then pieced together some other clues by looking at the .mat file in HDFView.

    enter image description here

    I came up with this that works . . .

    auto dataClass = data_set.getTypeClass();
    
    if (dataClass == H5T_FLOAT)
    {
        auto floatType = data_set.getFloatType();
        size_t byteSize = floatType.getSize();
    
        if (byteSize == 4)
        {
            type = "float";
        }
        else if (byteSize == 8)
        {
            type = "double";
        }
    }
    else if (dataClass == H5T_INTEGER)
    {
        auto intType = data_set.getIntType();
        size_t byteSize = intType.getSize();
    
        if (byteSize == 1)
        {
            type = "uint8";
        }
        else if (byteSize == 2)
        {
            type = "char";
        }
    }