C++ loads the file data into the in memory instance code at once

  • 2020-05-19 05:16:15
  • OfStack

C++ loads the file data into the in-memory instance code once

Question:

Earlier, I wrote a target detection SDK, which has two interfaces, loading the model from bin file and loading the model from memory. Later, I encountered cascading detection, that is, there were multiple bin model files. When I wanted to merge multiple bin files into one, I found that the corresponding loading interface had to be changed.

Solution:

In order not to change the interface, the following solutions are adopted:

(1) multiple bin files were spliced together, and the size of each file was recorded at the same time.

The merged files are: number of model files + model A size +... + model X size + model A parameters...

(2) use the following method to load the merged file into memory once


 /****************  Read the entire model into memory   ********************/
  std::ifstream infile(detModFile,std::ios::binary);
  if (!infile.is_open()) 
  { 
    printf( "connot open the model file: %s\n",detModFile); 
    return -1; 
  } 
  std::filebuf *pbuf = infile.rdbuf(); 
  //  Get file size 
  long filesize = static_cast<long>((pbuf->pubseekoff (0,std::ios::end,std::ios::in))); 
  pbuf->pubseekpos (0,std::ios::in);
  unsigned char* modelptr = new unsigned char[filesize]; 
  //  Read in the file contents 
  pbuf->sgetn ((char*)modelptr,filesize); 
  infile.close();   

  //  Number of acquired models 
  int model_num;
  int p_offset = 0;
  memcpy(&model_num,modelptr,sizeof(int));
  p_offset += sizeof(int);

  // Gets the size of each model 
  std::vector<int> each_size(model_num);
  int model_size;
  for (int i = 0; i < model_num; i++)
  {
    memcpy(&model_size,modelptr+p_offset,sizeof(int));
    p_offset += sizeof(int);
    each_size[i] = model_size;
  }

(3) then call the interface loaded from memory;

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: