title: 加载/释放 GRIB 消息

weight: 2

因为 ecCodes 仅能解码/编码加载过的 GRIB 消息,所以首先要加载消息。

有三个主要的函数用于加载一个 GRIB 消息。

  • codes_handle_new_from_file (NULL, f, PRODUCT_GRIB, &error)grib_handle_new_from_file

    从已经存在并使用 fopen 已打开的文件中加载 GRIB 消息。

  • codes_grib_handle_new_from_samples(NULL, 'regular_ll_sfc_grib2')grib_handler_new_from_samples

    从一个样例中加载 GRIB 消息,用于编码。后面会详细介绍。

  • codes_handle_new_from_index(index, &error)grib_handle_new_from_index

    从一个 index 中加载 GRIB 消息,index 需要事先创建好。后面会详细介绍。

上面三种加载函数将返回一个唯一的 grib handle,使用该 handle 可以操控已加载的 GRIB 消息。

无法直接访问包含已加载 GRIB 消息的缓存。缓存由 ecCodes 库内部处理。

任何 GRIB 消息占用的缓存都保存在内存中。

因此,当某个已加载的 GRIB 消息不再需要时,总应该调用 codes_handle_delete(handle) 函数释放其占用的空间。

示例:从文件中加载 GRIB 消息

  1. #include <iostream>
  2. #include <eccodes.h>
  3. using namespace std;
  4. int main(int argc, char** argv)
  5. {
  6. if(argc < 2)
  7. {
  8. cout<<"Usage: "<<argv[0]<<" grib_file_path";
  9. return 1;
  10. }
  11. const char* file_path = argv[1];
  12. FILE* in = fopen(file_path, "rb");
  13. if(!in)
  14. {
  15. cout<<"ERROR: unable to open file "<<file_path<<endl;
  16. return 1;
  17. }
  18. int err = 0;
  19. codes_handle *h = codes_handle_new_from_file(0, in, PRODUCT_GRIB, &err);
  20. if(h == nullptr)
  21. {
  22. cout<<"ERROR: unable to create handle from file "<<file_path<<endl;
  23. return 1;
  24. }
  25. codes_handle_delete(h);
  26. fclose(in);
  27. return 0;
  28. }