I've rolled my own. Here is a MCVE:
#include <Eigen/Core>
#include <Eigen/Sparse>
#include <iostream>
#include <fstream>
#include <vector>
using namespace Eigen;
typedef Triplet<int> Trip;
template <typename T, int whatever, typename IND>
void Serialize(SparseMatrix<T, whatever, IND>& m) {
std::vector<Trip> res;
int sz = m.nonZeros();
m.makeCompressed();
fstream writeFile;
writeFile.open("matrix", ios::binary | ios::out);
if(writeFile.is_open())
{
IND rows, cols, nnzs, outS, innS;
rows = m.rows() ;
cols = m.cols() ;
nnzs = m.nonZeros() ;
outS = m.outerSize();
innS = m.innerSize();
writeFile.write((const char *)&(rows), sizeof(IND));
writeFile.write((const char *)&(cols), sizeof(IND));
writeFile.write((const char *)&(nnzs), sizeof(IND));
writeFile.write((const char *)&(innS), sizeof(IND));
writeFile.write((const char *)&(outS), sizeof(IND));
writeFile.write((const char *)(m.valuePtr()), sizeof(T ) * m.nonZeros());
writeFile.write((const char *)(m.outerIndexPtr()), sizeof(IND) * m.outerSize());
writeFile.write((const char *)(m.innerIndexPtr()), sizeof(IND) * m.nonZeros());
writeFile.close();
}
}
template <typename T, int whatever, typename IND>
void Deserialize(SparseMatrix<T, whatever, IND>& m) {
fstream readFile;
readFile.open("matrix", ios::binary | ios::in);
if(readFile.is_open())
{
IND rows, cols, nnz, inSz, outSz;
readFile.read((char*)&rows , sizeof(IND));
readFile.read((char*)&cols , sizeof(IND));
readFile.read((char*)&nnz , sizeof(IND));
readFile.read((char*)&inSz , sizeof(IND));
readFile.read((char*)&outSz, sizeof(IND));
m.resize(rows, cols);
m.makeCompressed();
m.resizeNonZeros(nnz);
readFile.read((char*)(m.valuePtr()) , sizeof(T ) * nnz );
readFile.read((char*)(m.outerIndexPtr()), sizeof(IND) * outSz);
readFile.read((char*)(m.innerIndexPtr()), sizeof(IND) * nnz );
m.finalize();
readFile.close();
} // file is open
}
int main(int argc, char *argv[]){
int rows, cols;
rows = cols = 6;
SparseMatrix<double> A(rows,cols), B;
std::vector<Trip> trp, tmp;
trp.push_back(Trip(0, 0, rand()));
trp.push_back(Trip(1, 1, rand()));
trp.push_back(Trip(2, 2, rand()));
trp.push_back(Trip(3, 3, rand()));
trp.push_back(Trip(4, 4, rand()));
trp.push_back(Trip(5, 5, rand()));
trp.push_back(Trip(2, 4, rand()));
trp.push_back(Trip(3, 1, rand()));
A.setFromTriplets(trp.begin(), trp.end());
cout << A.nonZeros() << endl; // Prints 8
cout << A.size() << endl; // Prints 36
cout << A << endl; // Prints the matrix along with the sparse matrix stuff
Serialize(A);
Deserialize(B);
cout << B.nonZeros() << endl; // Prints 8
cout << B.size() << endl; // Prints 36
cout << B << endl; // Prints the reconstructed matrix along with the sparse matrix stuff
return 0;
}