Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1449912
  • 博文数量: 254
  • 博客积分: 8696
  • 博客等级: 中将
  • 技术积分: 2961
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-03 16:46
文章分类

全部博文(254)

文章存档

2015年(4)

2014年(18)

2013年(16)

2012年(8)

2011年(25)

2010年(2)

2009年(74)

2008年(107)

分类: C/C++

2013-08-26 18:31:01

ASN.1:ASN.1抽象语法标记(Abstract Syntax Notation One) ASN.1是一种 ISO/ITU-T 标准,描述了一种对数据进行表示、编码、传输和解码的数据格式。它提供了一整套正规的格式用于描述对象的结构,而不管语言上如何执行及这些数据的具体指代,也不用去管到底是什么样的应用程序。---百度百科

asn1c:The ASN.1 compiler is a tool for creating data encoders and decoders out of formal ASN.1 specifications.是由是Lev Walkin开发,按照ASN语法定义自己所需的数据结构,如struct,使用asn1c命令,能够自动生成所需的C/C++代码;在代码中使用依据的描述信息(asn_DEF_),调用对应的encode和decode完成编码和解码操作(BER、XER、PER)。

asn1c自动生成的代码只是为你完成编码和解码操作,并不包含其他如网络传输的接口。

把asn1c-0.9.24.tar.gz(这不是最新版本)下载,解包,依次按照configure,make,make install的步骤编译、安装;
安装成功后可使用asn1c命令。

以下是asn1c help文档中的实例:
rectangle.asn1:
RectangleModule1 DEFINITIONS ::=
BEGIN

Rectangle ::= SEQUENCE {
        height  INTEGER,
        width   INTEGER
}

END

执行命令
    asn1c -fnative-types rectangle.asn1
-fnative-types:Use the native machine's data types (int, double) whenever possible, instead of the compound INTEGER_t, ENUMERATED_t and REAL_t types.
命令执行成功,asn1c拷贝多份类型定义、编解码的.c和.h到当前目录中。

编辑文件main.c
include
#include
#include

static int write_out(const void *buffer, size_t size, void *app_key)
{
        FILE *out_fp = app_key;
        size_t wrote;
        wrote = fwrite(buffer, 1, size, out_fp);
        return (wrote == size)?0:-1;
}

int main(int ac, char **av)
{
        Rectangle_t *rectangle;
        asn_enc_rval_t ec;

        rectangle = calloc(1, sizeof(Rectangle_t));
        if(!rectangle)
        {
                perror("calloc failed");
                exit(71);
        }

        rectangle->height = 42;
        rectangle->width = 23;

        const char *filename = "Test";
        FILE *fp = fopen(filename, "wb");
        if(!fp)
        {
                perror("filename");
                exit(71);
        }
        
        ec = der_encode(&asn_DEF_Rectangle, rectangle, write_out, fp);
        fclose(fp);

        if(ec.encoded == -1)
        {
                perror("Count not encode Rectangle.\n");
                exit(65);
        }
        else
        {
                printf("Created with BER encoded Rectangle.\n");
        }

        xer_fprint(stdout, &asn_DEF_Rectangle, rectangle);
        return 0;
}

执行命令进行编译
cc -I. -o rencode *.c
如果提示undefined reference to 'asn_DEF_PDU' ;在命令中添加定义,如:
cc -DPDU=Rectangle -I. -o rencode *.c
"Rectangle"请根据自己需要作出修改。
asn_DEF_PDU在自动生成代码converter-sample.c的第8、9行有提及。

在执行cc命令后,如果在ld阶段提示main重复定义,则确定目录中是否包含converter-sample.c,如果是,则把它移除,重新编译链接。

阅读(14227) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~