Chinaunix
标题:
生成转换字节序函数的工具
[打印本页]
作者:
timespace
时间:
2008-08-13 13:29
标题:
生成转换字节序函数的工具
可用于网络编程时有很多结构体头文件,自动生成转换函数声明和定义,自己用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 编辑
]
ByteOrderTrans.rar
2008-08-13 21:23 上传
点击文件名下载附件
730 Bytes, 下载次数: 57
作者:
MMMIX
时间:
2008-08-13 20:46
要是提供代码的可下载版本就更完美了。
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2