asn1c

来源:互联网 发布:给自己的淘宝店铺取名 编辑:程序博客网 时间:2024/06/06 10:27
1,从https://github.com/vlm/asn1c 下载最新版的asn1c的源码;

2,打开Linux系统,将asn1c源码解压,找到INSTALL.md文件,根据INSTALL.md文件步骤安装即可;

3,将下述内容的asn文件保存为Rectangle.asn文件(假设所在文件夹目录为../RectangleTest,./目录为asn1c安装目录asn1c-master)

RectangleTest DEFINITIONS ::= BEGINRectangle ::= SEQUENCE {height INTEGER, -- Height of the rectanglewidth INTEGER -- Width of the rectangle}END

4,编译asn文件

 5,生成的C文件在RectangleTest目录中

6,将下述代码保存为main.c文件,

 1 #include <stdio.h> 2 #include <sys/types.h> 3 #include <Rectangle.h> /* Rectangle ASN.1 type */ 4 /* Write the encoded output into some FILE stream. */ 5 static int write_out(const void *buffer, size_t size, void *app_key) { 6 FILE *out_fp = app_key; 7 size_t wrote = fwrite(buffer, 1, size, out_fp); 8 return (wrote == size) ? 0 : -1; 9 }10 int main(int ac, char **av) {11 Rectangle_t *rectangle; /* Type to encode */12 asn_enc_rval_t ec; /* Encoder return value */13 /* Allocate the Rectangle_t */14 rectangle = calloc(1, sizeof(Rectangle_t)); /* not malloc! */15 if(!rectangle) {16 perror("calloc() failed ");17 exit(1);18 }19 /* Initialize the Rectangle members */20 rectangle->height = 42; /* any random value */21 rectangle->width = 23; /* any random value */22 /* BER encode the data if filename is given */23 if(ac < 2) {24 fprintf(stderr," specify filename for BER output\n");25 } else {26 const char *filename = av[1];27 FILE *fp = fopen(filename, "wb"); /* for BER output */28 if(!fp) {29 perror(filename);30 exit(1);31 }32 /* Encode the Rectangle type as BER (DER) */33 ec = der_encode(&asn_DEF_Rectangle, rectangle, write_out, fp);34 fclose(fp);35 if(ec.encoded == -1) {36 fprintf(stderr, "”Could not encode Rectangle (at %s)\n”",37 ec.failed_type ? ec.failed_type->name : "unknown");38 exit(1);39 } else {40 fprintf(stderr, "”Created %s with BER encoded Rectangle\n”", filename);41 }42 }43 /* Also print the constructed Rectangle XER encoded (XML) */44 xer_fprint(stdout, &asn_DEF_Rectangle, rectangle);45 return 0; /* Encoding finished successfully */46 }

7.输入gcc -I. -o rencode *.c ,生成recode文件

8,执行./recode,结果如下:

 

0 0
原创粉丝点击