14

I'm using HDF5 C++ API in HDF5 1.8.7 and would like to use an H5::Attribute instance to set a couple of scalar attributes in an H5::DataSet instance, but cannot find any examples. It's pretty cut and dry using the C API:

/* Value of the scalar attribute */ 
int point = 1;                         

/*
 * Create scalar attribute for the dataset, my_dataset.
 */
aid2  = H5Screate(H5S_SCALAR);
attr2 = H5Acreate(my_dataset, "Integer attribute", H5T_NATIVE_INT, aid2,H5P_DEFAULT);

/*
 * Write scalar attribute to my_dataset.
 */
ret = H5Awrite(attr2, H5T_NATIVE_INT, &point); 

/*
 * Close attribute dataspace.
 */
ret = H5Sclose(aid2); 

/*
 * Close attribute.
 */
ret = H5Aclose(attr2); 

For some strange reason, the H5::Attribute and H5::DataSet classes in the C++ API seem to be missing the necessary methods. If anyone can come up with a concrete example using the C++ API, I'd be very appreciative.

Marc
  • 4,546
  • 2
  • 29
  • 45

1 Answers1

18

if you have a Dataset object ds...

adding a string attribute...

StrType str_type(0, H5T_VARIABLE);
DataSpace att_space(H5S_SCALAR);
Attribute att = ds.createAttribute( "myAttribute", str_type, att_space );
att.write( str_type, "myString" );

adding an int attribute...

IntType int_type(PredType::STD_I32LE);
DataSpace att_space(H5S_SCALAR);
Attribute att = ds.createAttribute(" myAttribute", int_type, att_space );
int data = 77;
att.write( int_type, &data );
manuell
  • 7,528
  • 5
  • 31
  • 58
Sam Russell
  • 281
  • 2
  • 7
  • 5
    The string type should really be `StrType strtype(PredType::C_S1, H5T_VARIABLE);` – Simon Jul 15 '11 at 02:13
  • 1
    The createAttribute method is defined for H5::Object-s, so you can use the same idiom for attaching attributes to H5::Group -s, for example. – András Aszódi Oct 26 '13 at 09:11
  • @Simon: [either way works just fine](http://www.hdfgroup.org/HDF5/doc/cpplus_RM/classH5_1_1StrType.html#a502e6a4895bf51314204179e3f093a7f) – Jim Garrison Dec 10 '13 at 06:12
  • 3
    I got a segfault with `att.write( str_type, "myString" );` It worked with `att.write( str_type, std::string("myString"))`; – Joma Apr 30 '15 at 07:46
  • 1
    @Joma: I got a segfault as well; did you file a bug report? – user14717 Jul 17 '15 at 21:32