0%

GMT API C 在windows的使用

前期咨询了GMT开发者一些windows中使用GMT C API的问题,可以看这,发现直接使用GMT exe安装包中的库总是出现问题(可能和依赖有关系?和平台有关系?),最终选择了使用visual studio 2019进行源码编译lib,并调用API试验。

API C调用的一个例子源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include "gmt.h"
#pragma comment(lib, "gmt.lib")

int main(int argc, char* argv[]) {
void* API; /* The API control structure */
struct GMT_DATASET* D = NULL; /* Structure to hold input dataset */
struct GMT_GRID* G = NULL; /* Structure to hold output grid */
char input[GMT_STR16] = { "" }; /* String to hold virtual input filename */
char output[GMT_STR16] = { "" }; /* String to hold virtual output filename */
char args[128] = { "" }; /* String to hold module command arguments */

/* Initialize the GMT session */
API = GMT_Create_Session("test", 2U, 0, NULL);
/* Read in our data table to memory */
D = GMT_Read_Data(API, GMT_IS_DATASET, GMT_IS_FILE, GMT_IS_PLP, GMT_READ_NORMAL, NULL,
"table_5.11", NULL);
/* Associate our data table with a virtual file */
GMT_Open_VirtualFile(API, GMT_IS_DATASET, GMT_IS_PLP, GMT_IN, D, input);
/* Create a virtual file to hold the resulting grid */
GMT_Open_VirtualFile(API, GMT_IS_GRID, GMT_IS_SURFACE, GMT_OUT, NULL, output);
/* Prepare the module arguments */
sprintf_s(args, 128,"-R0/7/0/7 -I0.2 -D1 -St0.3 %s -G%s", input, output);
/* Call the greenspline module */
GMT_Call_Module(API, "greenspline", GMT_MODULE_CMD, args);
/* Obtain the grid from the virtual file */
G = GMT_Read_VirtualFile(API, output);
/* Close the virtual files */
GMT_Close_VirtualFile(API, input);
GMT_Close_VirtualFile(API, output);
/* Write the grid to file */
GMT_Write_Data(API, GMT_IS_GRID, GMT_IS_FILE, GMT_IS_SURFACE, GMT_READ_NORMAL, NULL,
"junk.nc", G);
/* Destroy the GMT session */
GMT_Destroy_Session(API);
};

  • 本例子在windows visual studio 2019中使用。Linux中应该非常简单,完全按照官网文档即可。
  • 加入#pragma comment(lib, “gmt.lib”) , 需gmt.lib路径正确,或者直接放到工程目录。
  • 设置visual studio的lib和include路径,区分Release和Debug,区分x64和x86。右键example工程-属性中设置。
  • 提前编译或者下载好GMT所依赖的库,参考vcpkg。因为vs在debug时需要调用这些库,并复制到debug目录下。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    yangleir@DESKTOP-FVRFATD MINGW64 ~/source/repos/example/x64/Debug
    $ ls *.dll

    expatd.dll* hdf5_hl_D.dll* LIBPQ.dll* sqlite3.dll*
    gdal204.dll* libcharset.dll* libssl-1_1-x64.dll* szip_D.dll*
    geos_cd.dll* libcrypto-1_1-x64.dll* libxml2.dll* webpd.dll*
    geosd.dll* libcurl-d.dll* lzmad.dll* zlibd1.dll*
    gmt.dll* libiconv.dll* netcdf.dll*
    hdf5_D.dll* libpng16d.dll* openjp2.dll*
  • 编译这个例子需要调用libcurl联网下载table_5.11文件。如果curl出现错误,可以跳过下载,修改代码中"@table_5.11""table_5.11"。并且手动下载这个文件。这儿仅测试GMT API,因此其他库出现的错误暂时不管,若出错可选择不下载数据。
  • sprintf函数已经停用,请使用sprintf_s。
    1
    sprintf_s(args, 128,"-R0/7/0/7 -I0.2 -D1 -St0.3 %s -G%s", input, output);
  • 编译这个例子,vs中按F5。然后通过命令窗口进入Debug或者Release目录,发现已经有exe文件。执行
    1
    2
    ./example # generate nc file through the API example
    gmt grdimage junk.nc -JM4c> junk.ps