TRIQS / h5

A high-level C++ interface to the hdf5 library
https://triqs.github.io/h5
Other
3 stars 7 forks source link

Writing an integer with c++ and reading it in python fails #7

Closed chuffa closed 3 years ago

chuffa commented 3 years ago

When I write an integer with c++ and try to load it using python it crashes because it expects a long but gets an integer. Reading and writing only in c++ or only in python works correctly though.

Code to reproduce:

c++:

#include <h5/h5.hpp>
#include <h5/scalar.hpp>

int main(){
    int x = 3, y = 0;
    auto arch = h5::file("writeInt.h5", 'a');

    h5::h5_write(arch, "integer", x);
    h5::h5_read(arch, "integer", y);

    std::cout << x << " " << y <<std::endl; // that works

    return 0;
} 

python code:

from h5 import *
with HDFArchive('writeInt.h5') as a:
    print(a)
    y = a['integer'] #error

print(y)

Error:


---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-3-4a6a02683c26> in <module>
      1 with HDFArchive('writeInt.h5') as a:
----> 2     x = a['integer']

~/TRIQS3/install/lib/python3.8/site-packages/h5/archive.py in __getitem__(self, key)
    203             for s in l[:-1]: a = a.get_raw(s)
    204             return a[l[-1]]
--> 205         return self.__getitem1__(key,self._reconstruct_python_objects)
    206 
    207     #-------------------------------------------------------------------------

~/TRIQS3/install/lib/python3.8/site-packages/h5/archive.py in __getitem1__(self, key, reconstruct_python_object, hdf5_format)
    225             hdf5_format = self._group.read_hdf5_format_from_key(key)
    226             if hdf5_format == "":
--> 227                 return bare_return()
    228 
    229         try :

~/TRIQS3/install/lib/python3.8/site-packages/h5/archive.py in <lambda>()
    215             bare_return = lambda: SubGroup
    216         elif self.is_data(key) :
--> 217             bare_return = lambda: self._read(key)
    218         else :
    219             raise KeyError("Key %s is of unknown type !!"%Key)

~/TRIQS3/install/lib/python3.8/site-packages/h5/archive_basic_layer.py in _read(self, key)
     60 
     61     def _read (self, key):
---> 62         return h5.h5_read(self._group, key)
     63 
     64     def _write(self, key, val) :

RuntimeError: .. Error occurred at Thu Mar 25 10:45:38 2021

.. Error .. calling C++ overload 
.. h5_read_bare(group g, std::string name) -> PyObject * 
.. in implementation of function _h5py.h5_read
.. C++ error was : 
h5 read. Type mismatch : expecting a long while the array stored in the hdf5 file has type int ```
Wentzell commented 3 years ago

Fixed in 4339a6d

Wentzell commented 3 years ago

Thank you @chuffa for pointing this out!