提示和技巧总是存在的。看看 Metaresc 库https://github.com/alexanderchuranov/Metaresc
它为类型声明提供接口,该接口也将为该类型生成元数据。基于元数据,您可以轻松地序列化/反序列化任何复杂的对象。开箱即用,您可以序列化/反序列化 XML、JSON、XDR、类 Lisp 表示法、C-init 表示法。
这是一个简单的例子:
#include <stdio.h>
#include <stdlib.h>
#include "metaresc.h"
TYPEDEF_STRUCT (host_t,
(char *, host),
int port,
);
TYPEDEF_STRUCT (config_t,
(host_t, local),
(host_t, remote),
(char *, name),
);
int main (int argc, char * argv[])
{
config_t config = {
.local = {
.host = "localhost",
.port = 8080,
},
.remote = {
.host = "google.com",
.port = 80,
},
.name = "service",
};
char * str = MR_SAVE_XML (config_t, &config);
if (str)
{
printf ("%s\n", str);
free (str);
}
return (EXIT_SUCCESS);
}
这个程序会输出
$ ./config
<?xml version="1.0"?>
<config>
<local>
<host>localhost</host>
<port>8080</port>
</local>
<remote>
<host>google.com</host>
<port>80</port>
</remote>
<name>service</name>
</config>
库适用于最新的 gcc 和 clang。