のあり方について書き出std::vector < std::string>コンテナをHDF5データセット?
質問
与えベクトルの文字列には、どうするのがベストな書き出しをHDF5データセット?その瞬間になっている以下のようなもの:
const unsigned int MaxStrLength = 512;
struct TempContainer {
char string[MaxStrLength];
};
void writeVector (hid_t group, std::vector<std::string> const & v)
{
//
// Firstly copy the contents of the vector into a temporary container
std::vector<TempContainer> tc;
for (std::vector<std::string>::const_iterator i = v.begin ()
, end = v.end ()
; i != end
; ++i)
{
TempContainer t;
strncpy (t.string, i->c_str (), MaxStrLength);
tc.push_back (t);
}
//
// Write the temporary container to a dataset
hsize_t dims[] = { tc.size () } ;
hid_t dataspace = H5Screate_simple(sizeof(dims)/sizeof(*dims)
, dims
, NULL);
hid_t strtype = H5Tcopy (H5T_C_S1);
H5Tset_size (strtype, MaxStrLength);
hid_t datatype = H5Tcreate (H5T_COMPOUND, sizeof (TempConainer));
H5Tinsert (datatype
, "string"
, HOFFSET(TempContainer, string)
, strtype);
hid_t dataset = H5Dcreate1 (group
, "files"
, datatype
, dataspace
, H5P_DEFAULT);
H5Dwrite (dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &tc[0] );
H5Dclose (dataset);
H5Sclose (dataspace);
H5Tclose (strtype);
H5Tclose (datatype);
}
最低限のものように変更に上るものとする。
- この可変長文字列
- へんて仮設コンテナ
私は制限がないのでかい店舗のデータだけでなく、例えばれているとは思いませんが、必 化合物 datatypeがある場合は、より良い関係ではないかと思います。
編集: での問題は、私は比較的馴染みのデータはC++の側でのHDF5側で必要なものです。
おります。
解決
[これを答える彼の助けのための dirkgently のに感謝します。
次を使用HDF5における可変長文字列を書き込むには、
// Create the datatype as follows
hid_t datatype = H5Tcopy (H5T_C_S1);
H5Tset_size (datatype, H5T_VARIABLE);
//
// Pass the string to be written to H5Dwrite
// using the address of the pointer!
const char * s = v.c_str ();
H5Dwrite (dataset
, datatype
, H5S_ALL
, H5S_ALL
, H5P_DEFAULT
, &s );
コンテナを作成するための一つの解決策は、個別に各要素を記述することです。これは hyperslabsするを使用して達成することができます。
例
class WriteString
{
public:
WriteString (hid_t dataset, hid_t datatype
, hid_t dataspace, hid_t memspace)
: m_dataset (dataset), m_datatype (datatype)
, m_dataspace (dataspace), m_memspace (memspace)
, m_pos () {}
private:
hid_t m_dataset;
hid_t m_datatype;
hid_t m_dataspace;
hid_t m_memspace;
int m_pos;
// ...
public:
void operator ()(std::vector<std::string>::value_type const & v)
{
// Select the file position, 1 record at position 'pos'
hsize_t count[] = { 1 } ;
hsize_t offset[] = { m_pos++ } ;
H5Sselect_hyperslab( m_dataspace
, H5S_SELECT_SET
, offset
, NULL
, count
, NULL );
const char * s = v.c_str ();
H5Dwrite (m_dataset
, m_datatype
, m_memspace
, m_dataspace
, H5P_DEFAULT
, &s );
}
};
// ...
void writeVector (hid_t group, std::vector<std::string> const & v)
{
hsize_t dims[] = { m_files.size () } ;
hid_t dataspace = H5Screate_simple(sizeof(dims)/sizeof(*dims)
, dims, NULL);
dims[0] = 1;
hid_t memspace = H5Screate_simple(sizeof(dims)/sizeof(*dims)
, dims, NULL);
hid_t datatype = H5Tcopy (H5T_C_S1);
H5Tset_size (datatype, H5T_VARIABLE);
hid_t dataset = H5Dcreate1 (group, "files", datatype
, dataspace, H5P_DEFAULT);
//
// Select the "memory" to be written out - just 1 record.
hsize_t offset[] = { 0 } ;
hsize_t count[] = { 1 } ;
H5Sselect_hyperslab( memspace, H5S_SELECT_SET, offset
, NULL, count, NULL );
std::for_each (v.begin ()
, v.end ()
, WriteStrings (dataset, datatype, dataspace, memspace));
H5Dclose (dataset);
H5Sclose (dataspace);
H5Sclose (memspace);
H5Tclose (datatype);
}
他のヒント
ここでは一部のコード書き込むためのベクターの可変長文字列を使用HDF5c++のAPIとなります。
を盛り込んだものの、その他の投稿:
- 利用H5T_C_S1とH5T_VARIABLE
- 使用
string::c_str()
取得ポインタの文字列 - 場所にポインタへ
vector
のchar*
渡のHDF5API
であ 不要 を高価なコピー文字列の例と strdup()
). c_str()
ポインタを返し、nullで終了データの基になる文字列です。この機能はありません。もちろん、文字列の埋め込みnullでは動作しません。
std::vector
は保証してい連続したカラムで使用 vector
や vector::data()
と同じ原配列がはるかにneater、より安全な、無骨、昔ながらのcうになっています。
#include "H5Cpp.h"
void write_hdf5(H5::H5File file, const std::string& data_set_name,
const std::vector<std::string>& strings )
{
H5::Exception::dontPrint();
try
{
// HDF5 only understands vector of char* :-(
std::vector<const char*> arr_c_str;
for (unsigned ii = 0; ii < strings.size(); ++ii)
arr_c_str.push_back(strings[ii].c_str());
//
// one dimension
//
hsize_t str_dimsf[1] {arr_c_str.size()};
H5::DataSpace dataspace(1, str_dimsf);
// Variable length string
H5::StrType datatype(H5::PredType::C_S1, H5T_VARIABLE);
H5::DataSet str_dataset = file.createDataSet(data_set_name, datatype, dataspace);
str_dataset.write(arr_c_str.data(), datatype);
}
catch (H5::Exception& err)
{
throw std::runtime_error(string("HDF5 Error in " )
+ err.getFuncName()
+ ": "
+ err.getDetailMsg());
}
}
あなたはクリーンなコードを見ている場合:私はあなたが文字列を取り、(任意のモードで)HDF5コンテナに保存しますファンクタを作成することをおすすめします。リチャード、私は間違ったアルゴリズムを使用し、再チェックしてください!
std::for_each(v.begin(), v.end(), write_hdf5);
struct hdf5 : public std::unary_function<std::string, void> {
hdf5() : _dataset(...) {} // initialize the HDF5 db
~hdf5() : _dataset(...) {} // close the the HDF5 db
void operator(std::string& s) {
// append
// use s.c_str() ?
}
};
それが始めるのに役立つしていますか?
また、同様の問題を第三にしたい"とベクトルの文字列として格納されます 属性.トリッキーもの属性を使用できませんのファンシdataspaceうhyperslabs(少なくとも、C++API)
がいずれの場合も役立つ場合がありますので、入力ベクトルの文字列を単一のエントリデータセット(例えば、常に期待されていることもあります。この場合すべての魔法の タイプ, ではなくdataspaceそのものです。
基本的には4つのステップで行います:
- 作
vector<const char*>
ポイントの文字列です。 - の作成
hvl_t
構造がこれらのベクターを含んです。 - をdatatype.この
H5::VarLenType
ラッピング(可変長)H5::StrType
. - を書く
hvl_t
型データセットである。
のんのこの方法はい詰めの入何HDF5考慮したスカラー値です。これで属性ではなく、データセット)であるようにします。
を選択するかどうかこのソリューションの各文字列に独自のデータセットに入れの所望の性能:ばんざいランダムアクセスの特定の文字列、あるんじゃないでしょうかい文字列を出したデータセットできるようにインデックス付きまだ読めてとして、このソリューションがで代用することもできます。
この短い期間ですがどのようなことは、C++のAPIと簡単なスカラーのデータセット:
#include <vector>
#include <string>
#include "H5Cpp.h"
int main(int argc, char* argv[]) {
// Part 0: make up some data
std::vector<std::string> strings;
for (int iii = 0; iii < 10; iii++) {
strings.push_back("this is " + std::to_string(iii));
}
// Part 1: grab pointers to the chars
std::vector<const char*> chars;
for (const auto& str: strings) {
chars.push_back(str.data());
}
// Part 2: create the variable length type
hvl_t hdf_buffer;
hdf_buffer.p = chars.data();
hdf_buffer.len = chars.size();
// Part 3: create the type
auto s_type = H5::StrType(H5::PredType::C_S1, H5T_VARIABLE);
s_type.setCset(H5T_CSET_UTF8); // just for fun, you don't need this
auto svec_type = H5::VarLenType(&s_type);
// Part 4: write the output to a scalar dataset
H5::H5File out_file("vtest.h5", H5F_ACC_EXCL);
H5::DataSet dataset(
out_file.createDataSet("the_ds", svec_type, H5S_SCALAR));
dataset.write(&hdf_buffer, svec_type);
return 0;
}
その代わりTempContainerの、あなたは(あなたはまた、それがTに一致するようにテンプレート化できる単純なのstd ::ベクトルを使用することができます - >のbasic_string。 このような何かます:
#include <algorithm>
#include <vector>
#include <string>
#include <functional>
class StringToVector
: std::unary_function<std::vector<char>, std::string> {
public:
std::vector<char> operator()(const std::string &s) const {
// assumes you want a NUL-terminated string
const char* str = s.c_str();
std::size_t size = 1 + std::strlen(str);
// s.size() != strlen(s.c_str())
std::vector<char> buf(&str[0], &str[size]);
return buf;
}
};
void conv(const std::vector<std::string> &vi,
std::vector<std::vector<char> > &vo)
{
// assert vo.size() == vi.size()
std::transform(vi.begin(), vi.end(),
vo.begin(),
StringToVector());
}
私はここにレオからヒントをもとに、私の解決策を掲載しています。の読み込みのstd::vector<std::string>
<のhref = "https://stackoverflow.com/a/15220532する能力を持つの利益のために/364818">https://stackoverflow.com/a/15220532/364818するます。
私は、CおよびC ++ APIを混ぜました。これを編集し、それを簡単に気軽にしてください。
あなたが読んで呼び出すときにHDF5のAPIがchar*
pointersのリストを返すことに注意してください。これらのchar*
ポインタは、そうでない場合は、メモリリークがあり、使用後に解放する必要があります。
使用例
H5::Attribute Foo = file.openAttribute("Foo");
std::vector<std::string> foos
Foo >> foos;
ここでのコード
const H5::Attribute& operator>>(const H5::Attribute& attr0, std::vector<std::string>& array)
{
H5::Exception::dontPrint();
try
{
hid_t attr = attr0.getId();
hid_t atype = H5Aget_type(attr);
hid_t aspace = H5Aget_space(attr);
int rank = H5Sget_simple_extent_ndims(aspace);
if (rank != 1) throw PBException("Attribute " + attr0.getName() + " is not a string array");
hsize_t sdim[1];
herr_t ret = H5Sget_simple_extent_dims(aspace, sdim, NULL);
size_t size = H5Tget_size (atype);
if (size != sizeof(void*))
{
throw PBException("Internal inconsistency. Expected pointer size element");
}
// HDF5 only understands vector of char* :-(
std::vector<char*> arr_c_str(sdim[0]);
H5::StrType stringType(H5::PredType::C_S1, H5T_VARIABLE);
attr0.read(stringType, arr_c_str.data());
array.resize(sdim[0]);
for(int i=0;i<sdim[0];i++)
{
// std::cout << i << "=" << arr_c_str[i] << std::endl;
array[i] = arr_c_str[i];
free(arr_c_str[i]);
}
}
catch (H5::Exception& err)
{
throw std::runtime_error(string("HDF5 Error in " )
+ err.getFuncName()
+ ": "
+ err.getDetailMsg());
}
return attr0;
}
私は遅れて相手にしていますが、私はセグメンテーション違反に関するご意見をもとにレオGoodstadtの答えを修正しました。私は、Linux上でですが、私はこのような問題を持っていません。私は、オープンH5Fileで指定された名前のデータセットにはstd ::ベクトルの文字列を記述すること、および他のSTDのベクターに結果のデータ・セットをリードバックするために2つの機能、1を書いた::文字列を。タイプ間の不必要なコピーをより最適化することができ、数回あっすることがあります。ここでは、書き込みと読み出しのためのコードを働いてます:
void write_varnames( const std::string& dsetname, const std::vector<std::string>& strings, H5::H5File& f)
{
H5::Exception::dontPrint();
try
{
// HDF5 only understands vector of char* :-(
std::vector<const char*> arr_c_str;
for (size_t ii = 0; ii < strings.size(); ++ii)
{
arr_c_str.push_back(strings[ii].c_str());
}
//
// one dimension
//
hsize_t str_dimsf[1] {arr_c_str.size()};
H5::DataSpace dataspace(1, str_dimsf);
// Variable length string
H5::StrType datatype(H5::PredType::C_S1, H5T_VARIABLE);
H5::DataSet str_dataset = f.createDataSet(dsetname, datatype, dataspace);
str_dataset.write(arr_c_str.data(), datatype);
}
catch (H5::Exception& err)
{
throw std::runtime_error(std::string("HDF5 Error in ")
+ err.getFuncName()
+ ": "
+ err.getDetailMsg());
}
}
で読みます:
std::vector<std::string> read_string_dset( const std::string& dsname, H5::H5File& f )
{
H5::DataSet cdataset = f.openDataSet( dsname );
H5::DataSpace space = cdataset.getSpace();
int rank = space.getSimpleExtentNdims();
hsize_t dims_out[1];
int ndims = space.getSimpleExtentDims( dims_out, NULL);
size_t length = dims_out[0];
std::vector<const char*> tmpvect( length, NULL );
fprintf(stdout, "In read STRING dataset, got number of strings: [%ld]\n", length );
std::vector<std::string> strs(length);
H5::StrType datatype(H5::PredType::C_S1, H5T_VARIABLE);
cdataset.read( tmpvect.data(), datatype);
for(size_t x=0; x<tmpvect.size(); ++x)
{
fprintf(stdout, "GOT STRING [%s]\n", tmpvect[x] );
strs[x] = tmpvect[x];
}
return strs;
}
私はHDF5について知らないが、あなたが使用することができます。
struct TempContainer {
char* string;
};
、その後の文字列をこのようにコピーします:
TempContainer t;
t.string = strdup(i->c_str());
tc.push_back (t);
これは、正確なサイズの文字列を割り当て、挿入または容器からの読み取り時にも多くが向上します(あなたの例では、この場合だけポインタにコピーされた配列、があります)。あなたはまたのstd ::ベクトルを使用することができます:
std::vector<char *> tc;
...
tc.push_back(strdup(i->c_str());