- 论坛徽章:
- 11
|
可用于网络编程时有很多结构体头文件,自动生成转换函数声明和定义,自己用Perl用写的,大家有时可能用得到
- #!/usr/bin/perl
- use strict;
- use warnings;
- my %to_net = (
- "short" => "htons",
- "int" => "htonl",
- "long" => "htonl",
- "INT16" => "htons",
- "UINT16" => "htons",
- "INT32" => "htonl",
- "UINT32" => "htonl",
- );
- my %to_host = (
- "short" => "ntohs",
- "int" => "ntohl",
- "long" => "ntohl",
- "INT16" => "ntohs",
- "UINT16" => "ntohs",
- "INT32" => "ntohl",
- "UINT32" => "ntohl",
- );
- my $definition = shift @ARGV;
- my $header = "ByteOrderTrans.h";
- my $source = "ByteOrderTrans.cpp";
- open DEF, "< $definition" or die "Can't open $definition: $!";
- open HEAD, "+> $header" or die "Can't open $header: $!";
- open BODY, "+> $source" or die "Can't open $source: $!";
- local $/;
- my $text = <DEF>;
- close DEF;
- my $var_re = qr/
- ^\s*
- (?:typedef\s+)?
- struct\s+
- (\w+)\s* #struct variable name
- \{
- ([^}]+) #member variables
- \}
- \s*\1?\s*;
- /x;
- my $mem_re = qr{
- (\w+)\s+ #member variable type
- (\w+)\s*$ #member variable name
- }x;
- my $hton_func;
- my $ntoh_func;
- while ( $text =~ /$var_re/msg ) {
- print HEAD "void hton_$1( $1 *p );\n"."void ntoh_$1( $1 *p );\n\n";
- $hton_func = "void hton_$1( $1 *p )\n{\n";
- $ntoh_func = "void ntoh_$1( $1 *p )\n{\n";
- foreach ( split /;/, $2 ) {
- if ( /$mem_re/ and exists $to_host{$1} ){
- $hton_func .= "\t p->$2 = $to_net{$1}(p->$2);\n";
- $ntoh_func .= "\t p->$2 = $to_host{$1}(p->$2);\n";
- }
- }
- print BODY $hton_func."}\n".$ntoh_func."}\n\n";
- }
- close HEAD;
- close BODY;
复制代码
[ 本帖最后由 timespace 于 2008-8-19 16:07 编辑 ] |
评分
-
查看全部评分
|