Chinaunix

标题: 生成转换字节序函数的工具 [打印本页]

作者: timespace    时间: 2008-08-13 13:29
标题: 生成转换字节序函数的工具
可用于网络编程时有很多结构体头文件,自动生成转换函数声明和定义,自己用Perl用写的,大家有时可能用得到


  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;

  4. my %to_net = (
  5.         "short" => "htons",
  6.         "int"        => "htonl",
  7.         "long"        => "htonl",
  8.         "INT16" => "htons",
  9.         "UINT16" => "htons",
  10.         "INT32" => "htonl",
  11.         "UINT32" => "htonl",
  12. );
  13. my %to_host = (
  14.         "short" => "ntohs",
  15.         "int"        => "ntohl",
  16.         "long"        => "ntohl",
  17.         "INT16" => "ntohs",
  18.         "UINT16" => "ntohs",
  19.         "INT32" => "ntohl",
  20.         "UINT32" => "ntohl",
  21. );
  22. my $definition = shift @ARGV;
  23. my $header        = "ByteOrderTrans.h";
  24. my $source  = "ByteOrderTrans.cpp";
  25. open DEF, "< $definition" or die "Can't open $definition: $!";
  26. open HEAD, "+> $header" or die "Can't open $header: $!";
  27. open BODY, "+> $source" or die "Can't open $source: $!";
  28. local $/;
  29. my $text = <DEF>;
  30. close DEF;

  31. my $var_re = qr/
  32.                    ^\s*
  33.                    (?:typedef\s+)?
  34.                    struct\s+
  35.                    (\w+)\s*        #struct variable name
  36.                    \{
  37.                        ([^}]+)     #member variables
  38.                    \}
  39.                    \s*\1?\s*;
  40.                /x;
  41. my $mem_re = qr{
  42.                    (\w+)\s+       #member variable type
  43.                    (\w+)\s*$      #member variable name
  44.                }x;
  45. my $hton_func;
  46. my $ntoh_func;
  47. while ( $text =~ /$var_re/msg ) {
  48.         print HEAD "void hton_$1( $1 *p );\n"."void ntoh_$1( $1 *p );\n\n";
  49.         $hton_func = "void hton_$1( $1 *p )\n{\n";
  50.         $ntoh_func = "void ntoh_$1( $1 *p )\n{\n";
  51.         foreach ( split /;/, $2 ) {
  52.                 if ( /$mem_re/ and exists $to_host{$1} ){
  53.                         $hton_func .= "\t p->$2 = $to_net{$1}(p->$2);\n";
  54.                         $ntoh_func .= "\t p->$2 = $to_host{$1}(p->$2);\n";
  55.                 }
  56.         }
  57.         print BODY $hton_func."}\n".$ntoh_func."}\n\n";
  58. }
  59. close HEAD;
  60. close BODY;
复制代码

[ 本帖最后由 timespace 于 2008-8-19 16:07 编辑 ]

ByteOrderTrans.rar

730 Bytes, 下载次数: 57


作者: MMMIX    时间: 2008-08-13 20:46
要是提供代码的可下载版本就更完美了。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2