From: Charles Mills Date: 2005-04-05T04:29:43+09:00 Subject: Re: Extension question Joe Van Dyk wrote: > On Apr 4, 2005 8:34 AM, Charles Mills wrote: > > > > > Are there any general rules of thumb that you use when writing > > extensions? > > > > http://www.ruby-talk.org/cgi-bin/scat.rb/ruby/ruby-talk/47700 > > > > You shouldn't be able to cause your extension to seg fault from Ruby. > > That may sound like a joke, but I just mean using StringValue, > > NUM2LONG, etc before you starting using Ruby objects in C. > > How should errors be handled in C extensions? For example, my C > extension was expecting a Ruby string, but it was passed an IO object. > static VALUE expecting_a_string(VALUE self, VALUE str) { StringValue(str); /* str is now definately a String so I can * use RSTRING(str)->ptr, RSTRING(str)->len * and pass it to rb_str_* methods */ return self; } > Or, what should I do when I try to open a file in C (the filename > being passed to the function) and the file doesn't exist? static VALUE open_and_use_file(VALUE self, VALUE path_str) { const char *path = StringValueCStr(path_str); FILE *stream = fopen(path, "r"); if (stream == NULL) rb_sys_fail(path); /* does not return */ /* stream is now ready to use ... */ } you can use rb_sys_fail() when fread, etc fails as well. -Charlie