gabriele renzi <rff_rff / remove-yahoo.it> wrote in message news:<wQknd.40392$Ni.1406459 / twister1.libero.it>...
> An article from Garrett Rooney just appeared at OnLamp.com
> you can read it at
> http://www.onlamp.com/pub/a/onlamp/2004/11/18/extending_ruby.html
> 
> As you may understand it talks about how to write C extensions for ruby.
> It's great to see more ruby in online magazines, who's the next one ? :)
> 
> PS
> I'm not related to the author or the page, I just found it and noticed 
> the author is not a frequent writer here, so I forwarded the notice :)

One thing I wish C extension authors would stop doing is manually
counting variable length argument lists.  From the article:

static VALUE
writer_begin_element (int argc, VALUE *argv, VALUE self)
{
  genxWriter w;
  VALUE xmlns, name;

  switch (argc):

....

If I'm not mistaken, this style of argument checking has already led
to more than one bug in the Ruby source code itself.  Knock it off and
use rb_scan_args().  Also, I find that starting all VALUE variables
with 'rb' leads to clearer code, since it makes it immediately obvious
which values are Ruby VALUE's versus C variables.

static VALUE
writer_begin_element (int argc, VALUE *argv, VALUE self)
{
  genxWriter w;
  VALUE rbName, rbXmlns;
  
  /* One mandatory argument, one optional argument */
  rb_scan_args(argc,argv,"11",&rbName,&rbXmlns);
          
  Check_Type(rbName,T_STRING);
  Check_Type(rbXmlns,T_STRING);

....

This is both shorter, more concise and easier to read all in one shot.
 It's also a smarter API, since in both cases the name is mandatory,
while the namespace is optional, afaict.  So, now the front end looks
like this:

Genx::Writer#begin_element(name,namespace=nil)

Other than a minor modification in GENX4R_ERR, checking against Qnil
vs 0, this code is identical.  No big, ugly switch.  No need to
manually raise an ArgumentError if the arg count is wrong.  Nice and
tidy.

Regards,

Dan