系统环境:Ubuntu16.04
1、下载源码包
sudo git clone https://github.com/vlm/asn1c.git
2、生成配置文件
sudo autoreconf -iv
3、编译
sudo ./configure
sudo make
sudo make install
4、完成之后,查看一下有么有asn1c命令
6、下面开始实例验证
创建一个文件:rectangle.asn,声明下长和宽
RectangleModule DEFINITIONS ::= BEGIN
Rectangle ::= SEQUENCE {
height INTEGER,
width INTEGER
}
END
上面的asn转换成C语言简单来说就是:
typedef struct Rectangle {
long height;
long width;
} Rectangle_t;
7、使用asn1c命令生成出一系列.c和.h文件
asn1c -no-gen-OER rectangle.asn
命令执行后会出现下面一堆东西
8、写个main.c测试asn的编解码,如下:
#include <stdio.h>
#include <sys/types.h>
#include <Rectangle.h>
#include <OCTET_STRING.h>
/* Rectangle ASN.1 type */
/* Write the encoded output into some FILE stream. */
static int write_out(const void *buffer, size_t size, void *app_key) {
FILE *out_fp = app_key;
size_t wrote = fwrite(buffer, 1, size, out_fp);
return (wrote == size) ? 0 : 1;
}
int main(int ac, char **av) {
Rectangle_t *rectangle; /* Type to encode */
asn_enc_rval_t ec; /* Encoder return value */
/* Allocate the Rectangle_t */
rectangle = calloc(1, sizeof(Rectangle_t)); /* not malloc! */
if(!rectangle) {
perror("calloc() failed");
exit(1);
}
/* Initialize the Rectangle members */
rectangle->height = 42; /* any random value */
rectangle->width = 23; /* any random value */
/* BER encode the data if filename is given */
if(ac < 2) {
fprintf(stderr, "Specify filename for BER output\n");
}
else {
const char *filename = av[1];
FILE *fp = fopen(filename, "wb"); /* for BER output */
if(!fp) {
perror(filename);
exit(1);
}
/* Encode the Rectangle type as BER (DER) */
ec = der_encode(&asn_DEF_Rectangle, rectangle, write_out, fp);
fclose(fp);
if(ec.encoded == 1) {
fprintf(stderr, "Could not encode Rectangle (at %s)\n",
ec.failed_type ? ec.failed_type->name : "unknown");
exit(1);
}
else {
fprintf(stderr, "Created %s with BER encoded Rectangle\n",filename);
}
}
/* Also print the constructed Rectangle XER encoded (XML) */
xer_fprint(stdout, &asn_DEF_Rectangle, rectangle);
return 0; /* Encoding finished successfully */
}
9、编译所有的文件
gcc -I. -o rencode *.c -DASN_DISABLE_OER_SUPPORT
结果报错:
删掉这个.c文件,再重新编译
rm converter-example.c
10、执行看下结果
附上另外一个例子教程,有兴趣可以看看:
http://lionet.info/asn1c/examples.html