/// <summary> /// /// </summary> /// <param name="varId"></param> /// <param name="attributeName"></param> /// <returns>null when attribute does not exist</returns> private NetCdfAttribute GetAttribute(int varId, string attributeName) { NetCdfDataType type; IntPtr lengthPtr; var status = NetCdfWrapper.nc_inq_att(id, varId, attributeName, out type, out lengthPtr); int length = lengthPtr.ToInt32(); if (status == (int)NetCdfWrapper.ResultCode.NC_ENOTATT) { return(null); } CheckResult(status); switch (type) { case NetCdfDataType.NC_CHAR: var charArray = new byte[length + 1]; IntPtr ptr = UTF8Marshal.BytesUTF8ToPtr(charArray); CheckResult(NetCdfWrapper.nc_get_att_text(id, varId, attributeName, ptr)); charArray[length] = 0; return(new NetCdfAttribute(attributeName, UTF8Marshal.PtrToStringUTF8(ptr))); case NetCdfDataType.NC_INT: var intArray = new int[length]; CheckResult(NetCdfWrapper.nc_get_att_int(id, varId, attributeName, intArray)); return(new NetCdfAttribute(attributeName, intArray[0])); case NetCdfDataType.NC_FLOAT: var floatArray = new float[length]; CheckResult(NetCdfWrapper.nc_get_att_float(id, varId, attributeName, floatArray)); return(new NetCdfAttribute(attributeName, floatArray[0])); case NetCdfDataType.NC_DOUBLE: var doubleArray = new double[length]; CheckResult(NetCdfWrapper.nc_get_att_double(id, varId, attributeName, doubleArray)); return(new NetCdfAttribute(attributeName, doubleArray[0])); default: throw new Exception( String.Format("Unknown type {0} for reading NetCDF attribute {1} from file {2}", type, attributeName, path)); } }
private void WriteAttribute(int varId, NetCdfAttribute ncAttribute) { var value = ncAttribute.Value; if (value is string) { var str = (string)value; CheckResult(NetCdfWrapper.nc_put_att_text(id, varId, ncAttribute.Name, new IntPtr(str.Length), UTF8Marshal.StringUTF8ToPtr(str))); } else if (value is double) { var d = (double)value; CheckResult(NetCdfWrapper.nc_put_att_double(id, varId, ncAttribute.Name, NetCdfDataType.NC_DOUBLE, new IntPtr(1), new[] { d })); } else if (value is float) { var i = (float)value; CheckResult(NetCdfWrapper.nc_put_att_float(id, varId, ncAttribute.Name, NetCdfDataType.NC_FLOAT, new IntPtr(1), new[] { i })); } else if (value is int) { var i = (int)value; CheckResult(NetCdfWrapper.nc_put_att_int(id, varId, ncAttribute.Name, NetCdfDataType.NC_INT, new IntPtr(1), new[] { i })); } else { throw new NotImplementedException(string.Format("NetCdf Attribute type '{0}' not implemented", value != null ? value.GetType().ToString() : "<null>")); } }