C extension authors: use rb_scan_args(); don't count argc

by Daniel Berger

If you're writing a C extension for Ruby, and you've got method that has optional arguments, be sure to use rb_scan_args(). Do not count argc. Read on if you want to know why.

7 Comments

Gregory
2007-04-04 10:04:46
I really am glad to see posts related to C extensions. This info always seems a bit hard to find.


Daniel, do you have good general references on how to do extensions with Ruby? A post on those would be grand.

Matthew Sporleder
2007-04-04 14:47:30
I'm not disagreeing, but what about using a va_list for variable numbers of arguments?
Daniel Berger
2007-04-04 16:48:20
Matthew - If you use va_args you're still in the same boat of manually counting arguments and raising exceptions by hand instead of letting rb_scan_args() do the work for you. That approach is probably even more error prone than what I showed in this article. So, please don't do that. :)
shev
2007-04-04 17:17:33
Great article. We need more of these :-)
Daniel Berger
2007-04-10 07:29:49
Greg, one of the better ones that I've seen was from Mark Volkmann at http://www.ociweb.com/mark/NFJS/RubyCExtensions.pdf. It has one or two mistakes, but it's pretty good.
Gregory
2007-04-11 06:38:53
Great, thanks!
Adel
2007-04-17 15:36:21
I was experimenting with C extensions and had a weird problem that i was not able to solve and i hope you can help me if possible.


I've built an extension and it is working fine in both a console and GTK applications. When i tried to use the extension in Rails, i had some issues. I am able to create an instance of the class but i am not able to send any messages to the defined methods in the extension! When i list the methods, i find only those inherited from the Object type.


any ideas?