public void H5AwriteTest1() { double[] x = { Math.PI }; IntPtr buf = Marshal.AllocHGlobal(8); Marshal.Copy(x, 0, buf, 1); hid_t att = H5A.create(m_v2_test_file, "A", H5T.IEEE_F64LE, m_space_scalar); Assert.IsTrue(att >= 0); Assert.IsTrue(H5A.write(att, H5T.NATIVE_DOUBLE, buf) >= 0); x[0] = 0.0; Assert.IsTrue(H5A.read(att, H5T.NATIVE_DOUBLE, buf) >= 0); Marshal.Copy(buf, x, 0, 1); Assert.IsTrue(x[0] == Math.PI); Assert.IsTrue(H5A.close(att) >= 0); att = H5A.create(m_v0_test_file, "A", H5T.IEEE_F64LE, m_space_scalar); Assert.IsTrue(att >= 0); Assert.IsTrue(H5A.write(att, H5T.NATIVE_DOUBLE, buf) >= 0); x[0] = 0.0; Assert.IsTrue(H5A.read(att, H5T.NATIVE_DOUBLE, buf) >= 0); Marshal.Copy(buf, x, 0, 1); Assert.IsTrue(x[0] == Math.PI); Assert.IsTrue(H5A.close(att) >= 0); Marshal.FreeHGlobal(buf); }
/// <summary> /// 写数据集属性 /// </summary> public void WriteDatasetAttribute(string datasetName, string attrName, string value) { H5DataSetId datasetId = H5D.open(_fileId, datasetName); H5DataTypeId typeId = H5T.copy(H5T.H5Type.C_S1); H5DataSpaceId spaceId = H5S.create(H5S.H5SClass.SCALAR); H5T.setSize(typeId, value.Length); H5AttributeId attrId = H5A.create(datasetId, attrName, typeId, spaceId); if (value != "") { H5Array <byte> buffer = new H5Array <byte>(Encoding.Default.GetBytes(value)); H5A.write(attrId, typeId, buffer); } if (typeId != null) { H5T.close(typeId); } if (spaceId != null) { H5S.close(spaceId); } if (attrId != null) { H5A.close(attrId); } if (datasetId != null) { H5D.close(datasetId); } }
private static void WriteAttribute(H5ObjectWithAttributes target, string name, string value) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Name must not be empty (or null)", "name"); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Value must not be empty or null", "value"); } H5DataTypeId dtype; byte[] strdata = EncodeStringData(value, out dtype); H5DataSpaceId spaceId = H5S.create(H5S.H5SClass.SCALAR); H5AttributeId attributeId = H5A.create(target, name, dtype, spaceId); H5A.write(attributeId, dtype, new H5Array <byte>(strdata)); H5A.close(attributeId); H5T.close(dtype); H5S.close(spaceId); }
public static int WritePrimitiveAttribute <T>(hid_t groupId, string name, Array attributes, string datasetName = null) //where T : struct { var tmpId = groupId; if (!string.IsNullOrWhiteSpace(datasetName)) { var datasetId = H5D.open(groupId, datasetName); if (datasetId > 0) { groupId = datasetId; } } int rank = attributes.Rank; ulong[] dims = Enumerable.Range(0, rank).Select(i => { return((ulong)attributes.GetLength(i)); }).ToArray(); ulong[] maxDims = null; var spaceId = H5S.create_simple(rank, dims, maxDims); var datatype = GetDatatype(typeof(T)); var typeId = H5T.copy(datatype); var attributeId = H5A.create(groupId, name, datatype, spaceId); GCHandle hnd = GCHandle.Alloc(attributes, GCHandleType.Pinned); var result = H5A.write(attributeId, datatype, hnd.AddrOfPinnedObject()); hnd.Free(); H5A.close(attributeId); H5S.close(spaceId); H5T.close(typeId); if (tmpId != groupId) { H5D.close(groupId); } return(result); }
/// <summary> /// Store a string in this *attribute*. /// </summary> public void Writes(string value) { using (H5Type dtype = GetDType()) { if (typeof(System.String) != dtype.PrimitiveType) { throw new InvalidCastException(dtype.PrimitiveType.ToString()); } long slen = dtype.Size; if (value.Length > slen - 1) { throw new IndexOutOfRangeException($"string longer than ({slen})"); } byte[] buf = new byte[slen]; Array.Copy(string1d.Enc.GetBytes(value), buf, value.Length); GCHandle pinnedArray = GCHandle.Alloc(buf, GCHandleType.Pinned); int status = H5A.write(ID, dtype.ID, pinnedArray.AddrOfPinnedObject()); pinnedArray.Free(); if (status < 0) { throw new H5LibraryException($"H5A.write() returned ({status})"); } } }
private bool setOMXFileAttributes() { // write OMX attributes H5DataSpaceId dspace; H5DataTypeId dtype; H5AttributeId attr; // OMX version dspace = H5S.create(H5S.H5SClass.SCALAR); dtype = H5T.copy(H5T.H5Type.C_S1); // string datatype H5T.setSize(dtype, dllVersion[0].Length); attr = H5A.create(fileId, omxVersionName, dtype, dspace); ASCIIEncoding ascii = new ASCIIEncoding(); H5A.write(attr, dtype, new H5Array <System.Byte>(ascii.GetBytes(dllVersion[0]))); H5A.close(attr); // OMX shape - only 2D tables dspace = H5S.create_simple(1, new long[] { 2 }); dtype = H5T.copy(H5T.H5Type.NATIVE_INT); attr = H5A.create(fileId, omxShapeAttr, dtype, dspace); int[] shape = new int[2]; shape[0] = (int)Shape[0]; shape[1] = (int)Shape[1]; H5A.write <int>(attr, dtype, new H5Array <int>(shape)); H5S.close(dspace); H5A.close(attr); return(true); }
private static void WriteFile(string filePath) { var file = H5F.create(filePath, H5F.CreateMode.ACC_TRUNC); var group = H5G.create(file, "/group"); H5G.close(group); const int RANK = 2; const int DIM0 = 3; const int DIM1 = 4; var dims = new long[RANK] { DIM0, DIM1 }; var dataSpace = H5S.create_simple(RANK, dims); var dataSet = H5D.create(file, "/group/dataset", H5T.H5Type.NATIVE_INT, dataSpace); H5S.close(dataSpace); var data = new int[DIM0, DIM1] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; H5D.write(dataSet, new H5DataTypeId(H5T.H5Type.NATIVE_INT), new H5Array <int>(data)); var dataType = new H5DataTypeId(H5T.H5Type.NATIVE_INT); dataSpace = H5S.create(H5S.H5SClass.SCALAR); var integerAttribute = H5A.create(dataSet, "int", dataType, dataSpace); H5A.write(integerAttribute, dataType, new H5Array <int>(new int[1] { 42 })); H5A.close(integerAttribute); H5S.close(dataSpace); //H5T.close(dataType); // Read-only. var str = "Hello, world!"; var strBytes = Encoding.ASCII.GetBytes(str); // There is a H5T.get_cset, but there does not seem to be a way of setting the character encoding, i.e. set_cset. dataType = H5T.copy(H5T.H5Type.C_S1); H5T.setSize(dataType, strBytes.Length); dataSpace = H5S.create(H5S.H5SClass.SCALAR); var stringAttribute = H5A.create(dataSet, "string", dataType, dataSpace); H5A.write(stringAttribute, dataType, new H5Array <byte>(strBytes)); H5A.close(stringAttribute); H5S.close(dataSpace); H5T.close(dataType); H5D.close(dataSet); H5F.close(file); }
public static (int success, hid_t CreatedgroupId) WriteStringAttributes(hid_t groupId, string name, IEnumerable <string> strs, string datasetName = null) { hid_t tmpId = groupId; if (!string.IsNullOrWhiteSpace(datasetName)) { hid_t datasetId = H5D.open(groupId, datasetName); if (datasetId > 0) { groupId = datasetId; } } // create UTF-8 encoded attributes hid_t datatype = H5T.create(H5T.class_t.STRING, H5T.VARIABLE); H5T.set_cset(datatype, H5T.cset_t.UTF8); H5T.set_strpad(datatype, H5T.str_t.SPACEPAD); int strSz = strs.Count(); hid_t spaceId = H5S.create_simple(1, new ulong[] { (ulong)strSz }, null); var attributeId = H5A.create(groupId, name, datatype, spaceId); GCHandle[] hnds = new GCHandle[strSz]; IntPtr[] wdata = new IntPtr[strSz]; int cntr = 0; foreach (string str in strs) { hnds[cntr] = GCHandle.Alloc( Encoding.UTF8.GetBytes(str), GCHandleType.Pinned); wdata[cntr] = hnds[cntr].AddrOfPinnedObject(); cntr++; } var hnd = GCHandle.Alloc(wdata, GCHandleType.Pinned); var result = H5A.write(attributeId, datatype, hnd.AddrOfPinnedObject()); hnd.Free(); for (int i = 0; i < strSz; ++i) { hnds[i].Free(); } H5A.close(attributeId); H5S.close(spaceId); H5T.close(datatype); if (tmpId != groupId) { H5D.close(groupId); } return(result, attributeId); }
public static void WriteAttribute(HDFAttributeDef hDFAttributeDef, H5DataTypeId dataTypeId, H5AttributeId attributeId) { if (hDFAttributeDef.Value == null || hDFAttributeDef.Value.ToString() == "") { return; } H5A.write <T>(attributeId, dataTypeId, new H5Array <T>(hDFAttributeDef.Value as T[])); }
public void H5AwriteTest2() { Assert.IsFalse( H5A.write(Utilities.RandomInvalidHandle(), Utilities.RandomInvalidHandle(), IntPtr.Zero) >= 0); Assert.IsFalse( H5A.write(Utilities.RandomInvalidHandle(), H5T.NATIVE_DOUBLE, IntPtr.Zero) >= 0); }
public static bool WriteScalarNumericAttribute <T>(hid_t hid, string key, T value, hid_t type) where T : struct { if (key == null) { throw new ArgumentNullException("key"); } var exists = H5A.exists(hid, key); if (exists < 0) { throw new Exception("H5A.exists failed"); } if (exists == 0) { var space = H5S.create(H5S.class_t.SCALAR); if (space < 0) { throw new Exception("Failed to create scalar space"); } var attribute = H5A.create(hid, key, type, space); if (attribute < 0) { H5S.close(space); throw new Exception(string.Format("Failed to create attribute \"{0}\"", key)); } H5S.close(space); object boxedValue = value; H5A.write(attribute, type, new PinnedObject(boxedValue)); H5A.close(attribute); return(true); } else { var attribute = H5A.open(hid, key); if (attribute < 0) { throw new Exception(string.Format("Failed to open attribute \"{0}\"", key)); } try { return(WriteScalarNumericAttribute(attribute, value, type)); } finally { H5A.close(attribute); } } }
public static bool WriteFixedStringAttribute(hid_t hid, string key, string value, bool utf8) { var exists = H5A.exists(hid, key); if (exists < 0) { throw new Exception("H5A.exists failed"); } if (exists == 0) // Attribute doesn't exist { var bytes = value.ToBytes(utf8); var type = CreateFixedStringType(bytes, utf8); var space = H5S.create(H5S.class_t.SCALAR); if (space < 0) { H5T.close(type); throw new Exception("Failed to create scalar space"); } var attribute = H5A.create(hid, key, type, space); if (attribute < 0) { H5S.close(space); H5T.close(type); throw new Exception(string.Format("Failed to create attribute \"{0}\"", key)); } H5A.write(attribute, type, new PinnedObject(bytes)); H5A.close(attribute); H5S.close(space); H5T.close(type); return(true); } else { var attribute = H5A.open(hid, key); if (attribute < 0) { throw new Exception(string.Format("Failed to open attribute \"{0}\"", key)); } try { return(WriteFixedStringAttribute(attribute, value, utf8)); } finally { H5A.close(attribute); } } }
// Generate string attribute // GroupName: target group for the new attribute // AttName: attribute name // AttContent: content for the attribute, has to be a string public static void StringAttributeGenerator(H5GroupId GroupName, string AttName, string AttContent) { char[] AttContentChar = AttContent.ToCharArray(); byte[] asciiStr = ASCIIEncoding.ASCII.GetBytes(AttContentChar); int length = asciiStr.Length; H5AttributeId attributeId = H5A.create(GroupName, AttName, H5T.create(H5T.CreateClass.STRING, length), H5S.create(H5S.H5SClass.SCALAR)); H5A.write(attributeId, H5T.create(H5T.CreateClass.STRING, length), new H5Array <byte>(asciiStr)); H5A.close(attributeId); }
// Generate double attributes // GroupName: target group for the new attribute // AttName: attribute name // AttContent: content for the attribute, has to be a single floating number, here 64bit double is used, to generate subgroups in Data public static void DoubleAttributeGenerator(H5GroupId GroupName, string AttName, double AttContent) { double[] AttArray = new double[1] { AttContent }; long[] dims = new long[1]; dims[0] = AttArray.Length; H5AttributeId attributeId = H5A.create(GroupName, AttName, H5T.copy(H5T.H5Type.NATIVE_DOUBLE), H5S.create_simple(1, dims)); H5A.write(attributeId, H5T.copy(H5T.H5Type.NATIVE_FLOAT), new H5Array <double>(AttArray)); H5A.close(attributeId); }
// Generate floating number attributes // GroupName: target group for the new attribute // AttName: attribute name // AttContent: content for the attribute, has to be a single floating number, here 32bit floating number is used, consider using 64bit double if necessary public static void NumberAttributeGenerator(H5GroupId GroupName, string AttName, float AttContent) { float[] AttArray = new float[1] { AttContent }; long[] dims = new long[1]; dims[0] = AttArray.Length; H5AttributeId attributeId = H5A.create(GroupName, AttName, H5T.copy(H5T.H5Type.NATIVE_FLOAT), H5S.create_simple(1, dims)); H5A.write(attributeId, H5T.copy(H5T.H5Type.NATIVE_FLOAT), new H5Array <float>(AttArray)); H5A.close(attributeId); }
private static H5AttributeId WriteStringAttribute(H5ObjectWithAttributes fileOrdatasetId, HDFAttributeDef hDFAttributeDef, H5DataSpaceId dataSpaceId, H5DataTypeId dataTypeId) { string attValue = Convert.ToString(hDFAttributeDef.Value); int stringLength = attValue.Length; H5T.setSize(dataTypeId, stringLength); H5AttributeId attributeId = H5A.create(fileOrdatasetId, hDFAttributeDef.Name, dataTypeId, dataSpaceId); byte[] bs = Encoding.Default.GetBytes(attValue); H5A.write(attributeId, dataTypeId, new H5Array <byte>(bs)); return(attributeId); }
private static void WriteAttribute(H5ObjectWithAttributes target, string name, long value) { H5DataTypeId dtype = H5T.copy(H5T.H5Type.NATIVE_LLONG); H5DataSpaceId spaceId = H5S.create(H5S.H5SClass.SCALAR); H5AttributeId attributeId = H5A.create(target, name, dtype, spaceId); H5A.write(attributeId, dtype, new H5Array <long>(new[] { value })); H5A.close(attributeId); H5T.close(dtype); H5S.close(spaceId); }
public static unsafe void Add(ContainerType container, long fileId, string groupName, string elementName, long typeId, void *dataPtr, long spaceId, long cpl = 0, long apl = 0) { long res; long groupId; if (H5L.exists(fileId, groupName) > 0) { groupId = H5G.open(fileId, groupName); } else { groupId = H5G.create(fileId, groupName); } long id; if (container == ContainerType.Dataset) { id = H5D.create(groupId, Encoding.UTF8.GetBytes(elementName), typeId, spaceId, dcpl_id: cpl, dapl_id: apl); if (id == -1) { throw new Exception("Could not create dataset."); } if ((int)dataPtr != 0) { res = H5D.write(id, typeId, spaceId, H5S.ALL, 0, new IntPtr(dataPtr)); } res = H5D.close(id); } else { id = H5A.create(groupId, Encoding.UTF8.GetBytes(elementName), typeId, spaceId, acpl_id: cpl); if (id == -1) { throw new Exception("Could not create attribute."); } if ((int)dataPtr != 0) { res = H5A.write(id, typeId, new IntPtr(dataPtr)); } res = H5A.close(id); } res = H5G.close(groupId); }
private static void WriteAttribute(H5ObjectWithAttributes target, string name, double[] value) { H5DataTypeId dtype = H5T.copy(H5T.H5Type.NATIVE_DOUBLE); H5DataSpaceId spaceId = H5S.create_simple(1, new[] { value.LongCount() }); H5AttributeId attributeId = H5A.create(target, name, dtype, spaceId); H5A.write(attributeId, dtype, new H5Array <double>(value)); H5A.close(attributeId); H5T.close(dtype); H5S.close(spaceId); }
public static void WriteLabelWorkingSet(long fileId_inp, bool overwrite_inp) { var LabelClassInfos = Labeling.GetAllIdsNamesAndMaterials(); int status = 0; ulong[] dims = new ulong[2]; dims[0] = 2; dims[1] = (ulong)LabelClassInfos.Count; long group_id = 0; if (overwrite_inp) { group_id = H5G.open(fileId_inp, "labelWorkingSet"); } else { group_id = H5G.create(fileId_inp, "labelWorkingSet"); } for (int i = 0; i < LabelClassInfos.Count; i++) { GCHandle labelID = GCHandle.Alloc(LabelClassInfos.ElementAt(i).Key, GCHandleType.Pinned); string labelClassName = LabelClassInfos.ElementAt(i).Value.Item1; long attr_id = H5A.open(group_id, labelClassName); if (attr_id >= 0) { //attribute exists status = H5A.write(attr_id, H5T.NATIVE_UINT32, labelID.AddrOfPinnedObject()); } else { //attribute has to be created attr_id = H5A.create(group_id, LabelClassInfos.ElementAt(i).Value.Item1, H5T.NATIVE_UINT32, H5S.create(H5S.class_t.SCALAR)); status = H5A.write(attr_id, H5T.NATIVE_UINT32, labelID.AddrOfPinnedObject()); } status = H5A.close(attr_id); } status = H5G.close(group_id); }
public static void WriteDataCube(H5FileId fileId, UInt16[,,] datacube) { H5GroupId dataGroup = H5G.create(fileId, "/data"); H5GroupId dataSubGroup = H5G.create(dataGroup, "DEsoftware"); long[] dims = new long[3] { datacube.GetLength(0), datacube.GetLength(1), datacube.GetLength(2) }; H5DataSpaceId spaceId = H5S.create_simple(3, dims); H5DataTypeId typeId = H5T.copy(H5T.H5Type.NATIVE_USHORT); H5DataSetId dataSetId = H5D.create(dataSubGroup, "data", typeId, spaceId); // create attribute emd_group_type for dataSubGroup, which is required to have value 1 int par = 1; long[] attdims = new long[1]; int[] AttArray = new int[1] { par }; dims[0] = AttArray.Length; H5AttributeId attributeId = H5A.create(dataSubGroup, "emd_group_type", H5T.copy(H5T.H5Type.NATIVE_UCHAR), H5S.create_simple(1, dims)); H5A.write(attributeId, H5T.copy(H5T.H5Type.NATIVE_INT), new H5Array <int>(AttArray)); H5A.close(attributeId); // write datacube to "data", which contains whole 3D datacube H5D.write <ushort>(dataSetId, typeId, new H5Array <ushort>(datacube)); // create three more array for three dimensions long[] dim1 = new long[1] { datacube.GetLength(0) }; double[] dimarray = new double [datacube.GetLength(0)]; spaceId = H5S.create_simple(3, dim1); typeId = H5T.copy(H5T.H5Type.NATIVE_DOUBLE); dataSetId = H5D.create(dataSubGroup, "dim1", typeId, spaceId); H5D.write <double>(dataSetId, typeId, new H5Array <double>(dimarray)); H5S.close(spaceId); H5T.close(typeId); H5D.close(dataSetId); H5G.close(dataGroup); H5G.close(dataSubGroup); }
static void WriteFile(string filePath) { var file = H5F.create(filePath, H5F.ACC_TRUNC); var group = H5G.create(file, "/group"); H5G.close(group); const int RANK = 2; const int DIM0 = 3; const int DIM1 = 4; var dims = new ulong[RANK] { DIM0, DIM1 }; var dataSpace = H5S.create_simple(RANK, dims, null); var dataSet = H5D.create(file, "/group/dataset", H5T.NATIVE_INT, dataSpace); H5S.close(dataSpace); var data = new int[DIM0, DIM1] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; H5D.write(dataSet, H5T.NATIVE_INT, H5S.ALL, H5S.ALL, H5P.DEFAULT, new PinnedObject(data)); var hello = "早上好!"; WriteStringAttribute(dataSet, "string", hello, true, false); WriteStringAttribute(dataSet, "string-ascii", "Hello, world!", false, false); WriteStringAttribute(dataSet, "string-vlen", hello, true, true); dataSpace = H5S.create(H5S.class_t.SCALAR); var doubleAttribute = H5A.create(dataSet, "double", H5T.NATIVE_DOUBLE, dataSpace); H5S.close(dataSpace); H5A.write(doubleAttribute, H5T.NATIVE_DOUBLE, new PinnedObject(new double[] { Math.PI })); H5A.close(doubleAttribute); H5D.close(dataSet); H5F.close(file); }
/// <summary> /// Writes the specified value to the file /// </summary> /// <typeparam name="T"></typeparam> /// <param name="_dataType"></param> /// <param name="_attributeId"></param> /// <param name="_value"></param> private static void WriteValue <T>( Hdf5DataType _dataType, Hdf5Identifier _attributeId, T _value) { T[] value = new T[1]; value[0] = _value; GCHandle arrayHandle = GCHandle.Alloc(value, GCHandleType.Pinned); var dataType = H5T.copy(_dataType.NativeType.Value).ToId(); int result = H5A.write(_attributeId.Value, dataType.Value, arrayHandle.AddrOfPinnedObject()); arrayHandle.Free(); H5T.close(dataType.Value); }
/// <summary> /// Store a numeric value in this *attribute*. /// </summary> /// <remarks> /// For writing a `string`, use `Writes()` instead! /// </remarks> public void Write <T>(T value) { using (H5Type dtype = GetDType()) { if (typeof(T) != dtype.PrimitiveType) { throw new InvalidCastException(dtype.PrimitiveType.ToString()); } T[] buf = new T[1] { value }; GCHandle pinnedArray = GCHandle.Alloc(buf, GCHandleType.Pinned); int status = H5A.write(ID, dtype.ID, pinnedArray.AddrOfPinnedObject()); pinnedArray.Free(); if (status < 0) { throw new H5LibraryException($"H5A.write() returned ({status})"); } } }
public static bool WriteScalarNumericAttribute <T>(hid_t attribute, T value, hid_t type) where T : struct { var space = H5A.get_space(attribute); if (space < 0) { throw new Exception("Failed to get space"); } if (H5S.get_simple_extent_type(space) != H5S.class_t.SCALAR) { H5S.close(space); throw new Exception("Not a scalar data space"); } H5S.close(space); var attributeType = H5A.get_type(attribute); if (attributeType < 0) { throw new Exception("Failed to get type"); } var attributeTypeClass = H5T.get_class(attributeType); H5T.close(attributeType); if (attributeTypeClass != H5T.class_t.INTEGER && attributeTypeClass != H5T.class_t.FLOAT) { throw new Exception("Not an integral or floating point data type"); } // TODO: // Check if value can be cast to type of this attribute. object boxedValue = value; H5A.write(attribute, type, new PinnedObject(boxedValue)); return(true); }
public static bool WriteVariableStringAttribute(hid_t hid, string key, IEnumerable <string> values, bool utf8) { if (key == null) { throw new ArgumentNullException("key"); } if (values == null) { throw new ArgumentNullException("values"); } var exists = H5A.exists(hid, key); if (exists < 0) { throw new Exception("H5A.exists failed"); } if (exists == 0) // Attribute doesn't exist { #if true var type = H5T.create(H5T.class_t.STRING, H5T.VARIABLE); if (type < 0) { throw new Exception("Failed to create string type"); } #else var type = H5T.copy(H5T.C_S1); if (type < 0) { throw new Exception("Failed to create string type"); } if (H5T.set_size(type, H5T.VARIABLE) < 0) { H5T.close(type); throw new Exception("Failed to set type size"); } #endif if (utf8) { if (H5T.set_cset(type, H5T.cset_t.UTF8) < 0) { H5T.close(type); throw new Exception("Failed to set cset"); } } if (H5T.set_strpad(type, H5T.str_t.NULLTERM) < 0) { H5T.close(type); throw new Exception("Failed to set strpad"); } var space = values.Count() == 1 ? H5S.create(H5S.class_t.SCALAR) : H5S.create_simple(1, new ulong[1] { (ulong)values.Count() }, null); if (space < 0) { H5T.close(type); throw new Exception("Failed to create data space"); } var attribute = H5A.create(hid, key, type, space); H5S.close(space); if (attribute < 0) { H5T.close(type); throw new Exception(string.Format("Failed to create attribute \"{0}\"", key)); } var pinnedObjects = new PinnedObject[values.Count()]; var data = new IntPtr[values.Count()]; int count = 0; foreach (string str in values) { var bytes = str.ToBytes(utf8); pinnedObjects[count] = new PinnedObject(bytes); data[count] = pinnedObjects[count]; count += 1; } H5A.write(attribute, type, new PinnedObject(data)); H5T.close(type); H5A.close(attribute); } else { // Attribute exists. var attribute = H5A.open(hid, key); if (attribute < 0) { throw new Exception(string.Format("Failed to open attribute \"{0}\"", key)); } var type = H5A.get_type(attribute); if (type < 0) { H5A.close(attribute); throw new Exception("Failed to get data type"); } var pinnedObjects = new PinnedObject[values.Count()]; var data = new IntPtr[values.Count()]; int count = 0; foreach (string str in values) { var bytes = str.ToBytes(utf8); pinnedObjects[count] = new PinnedObject(bytes); data[count] = pinnedObjects[count]; count += 1; } H5A.write(attribute, type, new PinnedObject(data)); H5T.close(type); H5A.close(attribute); } return(true); }
public static bool WriteFixedStringAttribute(hid_t attribute, string value, bool utf8) { if (value == null) { throw new ArgumentNullException("value"); } var space = H5A.get_space(attribute); if (space < 0) { throw new Exception("Failed to get data space"); } if (H5S.get_simple_extent_type(space) != H5S.class_t.SCALAR) { H5S.close(space); throw new Exception("Not a scalar data space"); } H5S.close(space); var type = H5A.get_type(attribute); if (type < 0) { throw new Exception("Failed to get type"); } var typeClass = H5T.get_class(type); if (typeClass != H5T.class_t.STRING) { H5T.close(type); throw new Exception("Not a string attribute"); } var isVariableString = H5T.is_variable_str(type); H5T.close(type); if (isVariableString < 0) { throw new Exception("H5T.is_variable_str failed"); } if (isVariableString > 0) { throw new Exception("Not a fixed string attribute"); } // TODO: Do we really need to create a new memory type here? var bytes = value.ToBytes(utf8); var memType = CreateFixedStringType(bytes, utf8); // TODO: type or memType here? H5A.write(attribute, memType, new PinnedObject(bytes)); H5T.close(memType); return(true); }
/// <summary> /// Currently does not support arrays /// </summary> /// <typeparam name="T"></typeparam> /// <param name="_objectId"></param> /// <param name="_title"></param> /// <param name="_value"></param> /// <returns></returns> public static Hdf5Attribute CreateAttribute <T>(Hdf5Identifier _objectId, string _title, T _value) { ulong[] sizes = new ulong[1] { 1 }; Hdf5Identifier dataspaceId; Hdf5Identifier attributeId; Hdf5Identifier typeId; Hdf5Attribute attribute = null; Type type = _value.GetType(); var datatype = TypeHelper.GetDataTypesEnum(type); if (datatype != Hdf5DataTypes.String) { var tempType = TypeHelper.GetNativeType(datatype); typeId = H5T.copy(tempType.Value).ToId(); var dataTypeObject = TypeHelper.GetDataTypeByType(typeId); var status = H5T.set_order(typeId.Value, H5T.order_t.LE); dataspaceId = H5S.create_simple(1, sizes, null).ToId(); attributeId = H5A.create(_objectId.Value, _title, typeId.Value, dataspaceId.Value).ToId(); if (attributeId.Value > 0) { WriteValue(dataTypeObject, attributeId, _value); } } else { string tempValue = Convert.ToString(_value); dataspaceId = H5S.create(H5S.class_t.SCALAR).ToId(); typeId = H5T.copy(H5T.C_S1).ToId(); int length = tempValue.Length + 1; var result = H5T.set_size(typeId.Value, new IntPtr(length)); attributeId = H5A.create(_objectId.Value, _title, typeId.Value, dataspaceId.Value).ToId(); IntPtr valueArray = Marshal.StringToHGlobalAnsi(tempValue); result = H5A.write(attributeId.Value, typeId.Value, valueArray); Marshal.FreeHGlobal(valueArray); } H5S.close(dataspaceId.Value); H5T.close(typeId.Value); H5A.close(attributeId.Value); if (attributeId.Value > 0) { attribute = new Hdf5Attribute { Value = _value, Name = _title, Id = attributeId }; } return(attribute); }
static void Main(string[] args) { try { // We will write and read an int array of this length. const int DATA_ARRAY_LENGTH = 12; // Rank is the number of dimensions of the data array. const int RANK = 1; // Create an HDF5 file. // The enumeration type H5F.CreateMode provides only the legal // creation modes. Missing H5Fcreate parameters are provided // with default values. H5FileId fileId = H5F.create("myCSharp.h5", H5F.CreateMode.ACC_TRUNC); // Create a HDF5 group. H5GroupId groupId = H5G.create(fileId, "/cSharpGroup"); H5GroupId subGroup = H5G.create(groupId, "mySubGroup"); // Close the subgroup. H5G.close(subGroup); // Prepare to create a data space for writing a 1-dimensional // signed integer array. long[] dims = new long[RANK]; dims[0] = DATA_ARRAY_LENGTH; // Put descending ramp data in an array so that we can // write it to the file. int[] dset_data = new int[DATA_ARRAY_LENGTH]; for (int i = 0; i < DATA_ARRAY_LENGTH; i++) { dset_data[i] = DATA_ARRAY_LENGTH - i; } // Create a data space to accommodate our 1-dimensional array. // The resulting H5DataSpaceId will be used to create the // data set. H5DataSpaceId spaceId = H5S.create_simple(RANK, dims); // Create a copy of a standard data type. We will use the // resulting H5DataTypeId to create the data set. We could // have used the HST.H5Type data directly in the call to // H5D.create, but this demonstrates the use of H5T.copy // and the use of a H5DataTypeId in H5D.create. H5DataTypeId typeId = H5T.copy(H5T.H5Type.NATIVE_INT); // Find the size of the type int typeSize = H5T.getSize(typeId); Console.WriteLine("typeSize is {0}", typeSize); // Set the order to big endian H5T.setOrder(typeId, H5T.Order.BE); // Set the order to little endian H5T.setOrder(typeId, H5T.Order.LE); // Create the data set. H5DataSetId dataSetId = H5D.create(fileId, "/csharpExample", typeId, spaceId); // Write the integer data to the data set. H5D.write(dataSetId, new H5DataTypeId(H5T.H5Type.NATIVE_INT), new H5Array <int>(dset_data)); // If we were writing a single value it might look like this. // int singleValue = 100; // H5D.writeScalar(dataSetId, // new H5DataTypeId(H5T.H5Type.NATIVE_INT), // ref singleValue); // Create an integer array to receive the read data. int[] readDataBack = new int[DATA_ARRAY_LENGTH]; // Read the integer data back from the data set H5D.read(dataSetId, new H5DataTypeId(H5T.H5Type.NATIVE_INT), new H5Array <int>(readDataBack)); // Echo the data for (int i = 0; i < DATA_ARRAY_LENGTH; i++) { Console.WriteLine(readDataBack[i]); } // Close all the open resources. H5D.close(dataSetId); // Reopen and close the data sets to show that we can. dataSetId = H5D.open(fileId, "/csharpExample"); H5D.close(dataSetId); dataSetId = H5D.open(groupId, "/csharpExample"); H5D.close(dataSetId); H5T.close(typeId); H5G.close(groupId); // Get H5O info H5ObjectInfo objectInfo = H5O.getInfoByName(fileId, "/csharpExample"); Console.WriteLine("header.space.message is {0}", objectInfo.header.space.message); Console.WriteLine("fileNumber is {0}", objectInfo.fileNumber); Console.WriteLine("address is {0}", objectInfo.address); Console.WriteLine("type is {0}", objectInfo.objectType.ToString()); Console.WriteLine("reference count is {0}", objectInfo.referenceCount); Console.WriteLine("modification time is {0}", objectInfo.modificationTime); Console.WriteLine("birth time is {0}", objectInfo.birthTime); Console.WriteLine("access time is {0}", objectInfo.accessTime); Console.WriteLine("change time is {0}", objectInfo.changeTime); Console.WriteLine("number of attributes is {0}", objectInfo.nAttributes); Console.WriteLine("header version is {0}", objectInfo.header.version); Console.WriteLine("header nMessages is {0}", objectInfo.header.nMessages); Console.WriteLine("header nChunks is {0}", objectInfo.header.nChunks); Console.WriteLine("header flags is {0}", objectInfo.header.flags); H5LinkInfo linkInfo = H5L.getInfo(fileId, "/cSharpGroup"); Console.WriteLine( "address: {0:x}, charSet: {1}, creationOrder: {2}", linkInfo.address, linkInfo.charSet, linkInfo.creationOrder); Console.WriteLine("linkType: {0}, softLinkSizeOrUD: {1}", linkInfo.linkType, linkInfo.softLinkSizeOrUD); // Reopen the group id to show that we can. groupId = H5G.open(fileId, "/cSharpGroup"); // Use H5L.iterate to visit links H5LIterateCallback myDelegate; myDelegate = MyH5LFunction; ulong linkNumber = 0; H5IterationResult result = H5L.iterate(groupId, H5IndexType.NAME, H5IterationOrder.INCREASING, ref linkNumber, myDelegate, 0); // Create some attributes H5DataTypeId attributeType = H5T.copy(H5T.H5Type.NATIVE_INT); long[] attributeDims = new long[1]; const int RAMP_LENGTH = 5; attributeDims[0] = RAMP_LENGTH; int[] ascendingRamp = new int[RAMP_LENGTH] { 1, 2, 3, 4, 5 }; int[] descendingRamp = new int[RAMP_LENGTH] { 5, 4, 3, 2, 1 }; int[] randomData = new int[RAMP_LENGTH] { 3, 123, 27, 6, 1 }; int[] readBackRamp = new int[RAMP_LENGTH]; // Call set buffer using H5Memory // Allocate memory from "C" runtime heap (not garbage collected) H5Memory typeConversionBuffer = new H5Memory(new IntPtr(DATA_ARRAY_LENGTH)); H5Memory backgroundBuffer = new H5Memory(new IntPtr(DATA_ARRAY_LENGTH)); // Set the property list type conversion and background buffers. H5PropertyListId myPropertyListId = H5P.create(H5P.PropertyListClass.DATASET_XFER); H5P.setBuffer(myPropertyListId, typeConversionBuffer, backgroundBuffer); // Test use of vlen // Create a vlen data type H5DataTypeId tid1 = H5T.vlenCreate(H5T.H5Type.NATIVE_UINT); H5DataSetId vDataSetId = H5D.create(fileId, "/vlenTest", tid1, spaceId); // Create a jagged array of integers. hvl_t[] vlArray = new hvl_t[DATA_ARRAY_LENGTH]; // HDF5 variable length data types require the use of void // pointers. C# requires that sections of code that deal // directly with pointer be marked // as unsafe. unsafe { for (int i = 0; i < DATA_ARRAY_LENGTH; i++) { IntPtr ptr = new IntPtr((i + 1) * sizeof(int)); // Allocate memory that is not garbage collected. vlArray[i].p = H5CrtHeap.Allocate( new IntPtr((i + 1) * sizeof(int)) ).ToPointer(); // Fill the array with integers = the row number int *intPointer = (int *)vlArray[i].p; for (int j = 0; j < i + 1; j++) { intPointer[j] = (int)i; } if (IntPtr.Size == 8) { vlArray[i].len = (ulong)i + 1; } else { vlArray[i].len = (uint)i + 1; } } // Write the variable length data H5D.write(vDataSetId, tid1, new H5Array <hvl_t>(vlArray)); // Create an array to read back the array. hvl_t[] vlReadBackArray = new hvl_t[DATA_ARRAY_LENGTH]; // Read the array back H5D.read(vDataSetId, tid1, new H5Array <hvl_t>(vlReadBackArray)); // Write the data to the console for (int i = 0; i < DATA_ARRAY_LENGTH; i++) { int *iPointer = (int *)vlReadBackArray[i].p; for (int j = 0; j < i + 1; j++) { Console.WriteLine(iPointer[j]); } } // Reclaim the memory that read allocated H5D.vlenReclaim(tid1, spaceId, new H5PropertyListId(H5P.Template.DEFAULT), new H5Array <hvl_t>(vlReadBackArray)); // Now read it back again using our own memory manager //H5AllocateCallback allocDelegate = new H5AllocCallback(userAlloc); H5FreeCallback freeDelegate = new H5FreeCallback(userFree); H5PropertyListId memManagerPlist = H5P.create(H5P.PropertyListClass.DATASET_XFER); unsafe { H5P.setVlenMemManager(memManagerPlist, userAlloc, IntPtr.Zero, freeDelegate, IntPtr.Zero); } // Read the array back H5D.read(vDataSetId, tid1, new H5DataSpaceId(H5S.H5SType.ALL), new H5DataSpaceId(H5S.H5SType.ALL), memManagerPlist, new H5Array <hvl_t>(vlReadBackArray)); // Write the data to the console for (int i = 0; i < DATA_ARRAY_LENGTH; i++) { int *iPointer = (int *)vlReadBackArray[i].p; for (int j = 0; j < i + 1; j++) { Console.WriteLine(iPointer[j]); } } // Reclaim the memory that read allocated using our free routines H5D.vlenReclaim(tid1, spaceId, memManagerPlist, new H5Array <hvl_t>(vlReadBackArray)); } H5S.close(spaceId); H5DataSpaceId attributeSpace = H5S.create_simple(1, attributeDims); H5AttributeId attributeId = H5A.create(groupId, "ascendingRamp", attributeType, attributeSpace); int offset = H5T.getOffset(attributeType); Console.WriteLine("Offset is {0}", offset); H5DataTypeId float32BE = H5T.copy(H5T.H5Type.IEEE_F32BE); H5T.Norm norm = H5T.getNorm(float32BE); Console.WriteLine("Norm is {0}", norm); int precision = H5T.getPrecision(float32BE); Console.WriteLine("Precision is {0}", precision); H5FloatingBitFields bitFields = H5T.getFields(float32BE); Console.WriteLine("getFields: sign bit position: {0}", bitFields.signBitPosition); Console.WriteLine("getFields: exponent bit position: {0}", bitFields.exponentBitPosition); Console.WriteLine("getFields: number of exponent bits: {0}", bitFields.nExponentBits); Console.WriteLine("getFields: mantissa bit position: {0} ", bitFields.mantissaBitPosition); Console.WriteLine("getFields: number of mantissa bits: {0}", bitFields.nMantissaBits); Console.Write("{0}", bitFields); // Write to an attribute H5A.write <int>(attributeId, attributeType, new H5Array <int>(ascendingRamp)); // Read from an attribute H5A.read <int>(attributeId, attributeType, new H5Array <int>(readBackRamp)); // Echo results Console.WriteLine("ramp elements are: "); foreach (int rampElement in readBackRamp) { Console.WriteLine(" {0}", rampElement); } H5A.close(attributeId); // Create and write two more attributes. attributeId = H5A.createByName(groupId, ".", "descendingRamp", attributeType, attributeSpace); H5A.write <int>(attributeId, attributeType, new H5Array <int>(descendingRamp)); H5A.close(attributeId); attributeId = H5A.createByName(groupId, ".", "randomData", attributeType, attributeSpace); H5A.write <int>(attributeId, attributeType, new H5Array <int>(randomData)); // Read back the attribute data H5A.read <int>(attributeId, attributeType, new H5Array <int>(readBackRamp)); Console.WriteLine("ramp elements are: "); foreach (int rampElement in readBackRamp) { Console.WriteLine(" {0}", rampElement); } H5A.close(attributeId); // Iterate through the attributes. long position = 0; H5AIterateCallback attributeDelegate; attributeDelegate = MyH5AFunction; H5ObjectInfo groupInfo = H5O.getInfo(groupId); Console.WriteLine( "fileNumber: {0}, total space: {1}, referceCount: {2}, modification time: {3}", groupInfo.fileNumber, groupInfo.header.space.total, groupInfo.referenceCount, groupInfo.modificationTime); // While iterating, collect the names of all the attributes. ArrayList attributeNames = new ArrayList(); H5A.iterate(groupId, H5IndexType.CRT_ORDER, H5IterationOrder.INCREASING, ref position, attributeDelegate, (object)attributeNames); // Write out the names of the attributes foreach (string attributeName in attributeNames) { Console.WriteLine("attribute name is {0}", attributeName); } // Demonstrate H5A.openName attributeId = H5A.openName(groupId, "descendingRamp"); Console.WriteLine("got {0} by name", H5A.getName(attributeId)); H5A.close(attributeId); // Demonstrate H5A.getNameByIndex string secondAttribute = H5A.getNameByIndex(groupId, ".", H5IndexType.CRT_ORDER, H5IterationOrder.INCREASING, 1); Console.WriteLine("second attribute is named {0}", secondAttribute); // Demonstrate H5G.getInfo H5GInfo gInfo = H5G.getInfo(groupId); Console.WriteLine( "link storage: {0}, max creation order: {1}, nLinks: {2}", gInfo.linkStorageType, gInfo.maxCreationOrder, gInfo.nLinks); // Demonstrate H5A.getSpace //attributeId = H5A.openByName(groupId, ".", "descendingRamp"); attributeId = H5A.open(groupId, "descendingRamp"); H5DataSpaceId rampSpaceId = H5A.getSpace(attributeId); H5S.close(rampSpaceId); // Demonstrate H5A.getType H5DataTypeId rampTypeId = H5A.getType(attributeId); Console.WriteLine("size of ramp data type is {0} bytes.", H5T.getSize(rampTypeId)); H5T.close(rampTypeId); // Demonstrate H5A.getInfo H5AttributeInfo rampInfo = H5A.getInfo(attributeId); Console.WriteLine( "characterset: {0}, creationOrder: {1}, creationOrderValid: {2}, dataSize: {3}", rampInfo.characterSet, rampInfo.creationOrder, rampInfo.creationOrderValid, rampInfo.dataSize); // Demonstrate H5A.Delete H5A.Delete(groupId, "descendingRamp"); //H5A.DeleteByName(groupId, ".", "descendingRamp"); // Iterate through the attributes to show that the deletion // was successful. position = 0; ArrayList namesAfterDeletion = new ArrayList(); H5A.iterate(groupId, H5IndexType.CRT_ORDER, H5IterationOrder.DECREASING, ref position, attributeDelegate, (object)namesAfterDeletion); H5G.close(groupId); H5F.close(fileId); // Reopen and reclose the file. H5FileId openId = H5F.open("myCSharp.h5", H5F.OpenMode.ACC_RDONLY); H5F.close(openId); // Set the function to be called on error. unsafe { H5AutoCallback myErrorDelegate = new H5AutoCallback(myErrorFunction); H5E.setAuto(0, myErrorDelegate, IntPtr.Zero); } // Uncomment the next line if you want to generate an error to // test H5E.setAuto // H5G.open(openId, "noGroup"); } // This catches all the HDF exception classes. Because each call // generates a unique exception, different exception can be handled // separately. For example, to catch open errors we could have used // catch (H5FopenException openException). catch (HDFException e) { Console.WriteLine(e.Message); } Console.WriteLine("Processing complete!"); Console.ReadLine(); }
public void Create(string key, object value) { Host.With((id) => { long dataspace = 0; long typeId = 0; long attributeId = 0; try { if (value is Array) { var array = (Array)value; dataspace = H5S.create_simple(array.Rank, array.Shape(), null); throw new NotImplementedException("Scalar attributes only"); } else { dataspace = H5S.create(H5S.class_t.SCALAR); } IntPtr nativeMemory; if (value is String) { var str = (string)value; typeId = H5T.copy(H5T.C_S1); H5T.set_size(typeId, new IntPtr(str.Length)); nativeMemory = Marshal.StringToHGlobalAnsi(str); } else if (value is long) { var l = new long[] { (long)value }; typeId = H5T.copy(H5T.NATIVE_INT64); nativeMemory = Marshal.AllocHGlobal(sizeof(long)); Marshal.Copy(l, 0, nativeMemory, 1); } else { throw new NotImplementedException("Unsupported attribute type: " + value.GetType().Name); } attributeId = H5A.create(id, key, typeId, dataspace); H5A.write(attributeId, typeId, nativeMemory); Marshal.FreeHGlobal(nativeMemory); } finally { if (attributeId > 0) { H5A.close(attributeId); } if (typeId > 0) { H5T.close(typeId); } if (dataspace > 0) { H5S.close(dataspace); } } }); }