readme.ext, which is linked in ruby guides as one of the main resources to develop ruby extensions, states the following:
Notice Ruby does not allow arbitrary pointer values to be a VALUE. They should be pointers to the structures which Ruby knows about. The known structures are defined in
<ruby.h>
.
So,
Thanks!
This covers all the basics, including how to use C structures with managed exposure as Ruby objects, how all the macros and functions work, and a reference to many of the functions: http://media.pragprog.com/titles/ruby3/ext_ruby.pdf
How you manage C objects associated with Ruby ones depends partly on the relationship you want to establish. You could simply create regular Ruby objects from within C, and just speed up one or two bits of complex maths for instance. Then you'd work more with VALUE
s, at least on input to all the methods. You also get access to all of Ruby's dynamics and introspection this way, so could have an extension that worked on instance variables by finding those that were of interest in the object without knowing in advance what they were called.
However, there are macros and helper functions from ruby.h
that help with hooking into Ruby's garbage collection for C structs and for arbitrary C data - types usually managed via malloc
. For example the Data_Wrap_Struct
function allows you to create an object which is effectively a C struct when you process it in your extension, but will otherwise be handled as a regular Ruby object (for assignment to variables etc). See the CD Jukebox example in the document I linked - there are several related functions you need to use to ensure your code plays correctly with Ruby's memory management.