Ubuntu搭建asn环境并简单实例验证

系统环境: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、执行看下结果
./rencode
附上另外一个例子教程,有兴趣可以看看:
http://lionet.info/asn1c/examples.html

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值