I'm trying to write and read VlGMM
from VLFeat to a binary file, in particular its component void *means
. You can find the class code here.
This is the 2 functions that I've written:
void writeVlGMM(const std::string &name, VlGMM* gmm){
std::ofstream out(name,std::ios_base::binary);
const void *means = vl_gmm_get_means(gmm); //dimension*numComponents elements
out.write((char *) &means, sizeof(means));
for(int i=0;i<dimension*numComponents;i++)
std::cout<<*((float*)(means)+i)<<" ";
std::cout<<std::endl;
}
void readVlGMM(vl_type dataType, const std::string &name, VlGMM* gmm, vl_size dimension, vl_size numComponents){
std::ifstream in( name, std::ios::binary );
vl_size size = vl_get_type_size(dataType) ;
void *means = vl_calloc (numComponents * dimension, size) ;
in.read((char *) &means, sizeof(means));
}
If I try to print means
values in both functions through this code (notice that I know that means is filled with floating points):
for(int i=0;i<dimension*numComponents;i++)
std::cout<<*((float*)(means)+i)<<" ";
The printed values are the same in the same program execution, so I guess that the code above works. Anyway, I think that what I'm writing in the file is the pointer value, not the mean's
value themselves! Is it possible that in different program executions the code above is not going to work?
This is because when the program execution terminates gmm
is deallocated and so means
, and the saved pointer is meaningless.
Is this correct? How can I solve the problem?
Is it possible that in different program executions the code above is not going to work?
Yes, it's about as possible as 1+1==2
.
Is this correct?
Absolutely.
How can I solve the problem?
Write and read the array rather than its address:
vl_size size = vl_get_type_size(dataType);
const void *means = vl_gmm_get_means(gmm)
out.write(static_cast<const char*>(means), numComponents * dimension * size);
/// ...
vl_size size = vl_get_type_size(dataType);
void *means = vl_calloc (numComponents * dimension, size) ;
in.read(static_cast<char*>(means), numComponents * dimension * size);