converting from c struct to function

Hey Guys,

I need your help where I have a C structure and I want it to be converted into corresponding function.

Example:

typedef    struct
{
    unsigned long    LineNum;      //1025-4032
    unsigned short    KeyNum;    /*tbd*/
    char        Key;                      /*between 1-3*/
    char        Choice ;                /*1 if just changed*/
}MY_KEY_STATE;

...needs to be converted into function below:

void export_MY_KEY_STATE(cOBJ *OutStr, MY_KEY_STATE a)
{
    AddULongToObject(OutStr,   "LineNum",           a.LineNum     );  //1025-4032
    AddUShortToObject(OutStr,  "KeyNum",           a.KeyNum      ); /*tbd*/
    AddCharToObject(OutStr,    "Key",       a.Key  ); /*between 1-3*/
    AddCharToObject(OutStr,    "Choice",    a.Choice);                /*1 if just changed*/
}

So, can we do the above conversion using shell script on Linux/Unix?

Note: The comments in the struct as intact in the function.

Thanks!
skyOS

How about this perl script ? It would work also for an input file with various typedefs one after the other.

#!/usr/bin/perl
$debug = 0;
$/ = "typedef\s+struct";
while(<>) {
  %type2method = (
    unsigned_long => AddULongToObject,
    unsigned_short => AddUShortToObject,
    char => AddCharToObject,
  );
  if (m,\s*\{\s*(.*)\}\s*(.*?)\s*;,s) {
    $funtype = $2;
    print STDERR "funtype=$funtype"."\n" if $debug >= 1;
    @lines = split(/\r?\n/, $1);
    print "void export_$funtype(cOBJ *OutStr, $funtype a)\n\{\n";
    foreach $line (@lines) {
      $line =~ s/^\s*//;
      @parts = split(/;/, $line);
      $comment = @parts[$#parts];
      @tokens = split(/\s+/, @parts[0]);
      $varname = @tokens[$#tokens];
      $type = join("_", @tokens[0..$#tokens-1]);
      $method = $type2method{$type};
      print STDERR "type=$type, method=$method, varname=$varname, comment=$comment\n" if $debug >= 1;
      print "\t${method}(OutStr,\\"$varname\",\ta.$varname\t);$comment\n";
    }
    print "\}\n";
  } else {
    print STDERR "no typedef pattern match found\n";
    exit 1;
  }
}