maynull
maynull

Reputation: 2046

How to write a dataset with HDF.PInvoke?

I'm trying to write arrays into an HDF5 file in C#, using HDF.PInvoke.

I've made a simple program that writes a 3x3 array into an HDF5 file, but when I opened it, the result is not the same as the array.

using HDF.PInvoke;
using System.Globalization;
using System.IO;

using System.Runtime.InteropServices;


namespace WindowsFormsApp3
{
    public unsafe partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            string currentPath = Path.GetDirectoryName(Application.ExecutablePath);     
            Directory.SetCurrentDirectory(currentPath);                                 

            long file_id = H5F.create(@"weights.h5", H5F.ACC_TRUNC, H5P.DEFAULT, H5P.DEFAULT);

            int[,] arrInt3 = { { 1, 2, 3 }, { 3, 2, 1 }, { 3, 2, 1 } };

            ulong[] dims = {3,3};

            long space_id = H5S.create_simple(2, dims, null);      

            long dataset_id = H5D.create(file_id, "/dset", H5T.STD_I32BE, space_id, H5P.DEFAULT, H5P.DEFAULT, H5P.DEFAULT);

            GCHandle pinnedArray = GCHandle.Alloc(arrInt3, GCHandleType.Pinned);
            IntPtr pointer = pinnedArray.AddrOfPinnedObject();

            long write_id = H5D.write(dataset_id, H5T.NATIVE_INT32, H5S.ALL, H5S.ALL, H5P.DEFAULT, pointer);


            long status = H5D.close(dataset_id);
            long status2 = H5S.close(space_id);
            long status3 = H5F.close(file_id);
        }
    }
}

When I open the file in Python, the result is

>>> f.root.dset
/dset (Array(1, 2)) ''
  atom := Int32Atom(shape=(), dflt=0)
  maindim := 0
  flavor := 'numpy'
  byteorder := 'big'
  chunkshape := None

>>> f.root.dset[:]
array([[0, 0]])

Why is it different from the original array? I'd like know where I've made mistakes.

Upvotes: 1

Views: 968

Answers (1)

SOG
SOG

Reputation: 912

Not sure how to do this using HDF.PInvoke but, if you are not bound to this particular library, you may want to check HDFql (as it greatly simplifies how to handle HDF5 files).

Writing an 3x3 array into an HDF5 file using HDFql in C# can be done as follows:

public Form1()
{
    InitializeComponent();

    string currentPath = Path.GetDirectoryName(Application.ExecutablePath);     

    Directory.SetCurrentDirectory(currentPath);    

    HDFql.Execute("CREATE TRUNCATE FILE weights.h5");

    int[,] arrInt3 = { { 1, 2, 3 }, { 3, 2, 1 }, { 3, 2, 1 } };

    HDFql.Execute("CREATE DATASET weights.h5 /dset AS INT(3, 3) VALUES FROM MEMORY " + HDFql.VariableTransientRegister(arrInt3));
}

Please check this webpage for additional examples on how to use HDFql in C#.

Upvotes: 2

Related Questions