Writing Ruby Extensions with RubyCocoa

Most Ruby users know that extensions to Ruby can be written in C. This makes it possible to write optimized C implementations of Ruby classes and to access any C-level API from Ruby.

The process is described in Programming Ruby and in the README.EXT file in the Ruby source distribution.

RubyCocoa provides a simpler alternative. If we wrap our C functions and data structures in Objective-C classes, RubyCocoa will do the rest of the translation work. This short guide presents an example.

Copyright

Copyright © 2006, by Tim Burks, some rights reserved.

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 2.5 License.

What do you think of this book? Post your comment or suggestion below!

Comments (1) post
  1. Eric Meyers Sun Oct 14 14:54:19 +0000 2007

    Wow. This is some good stuff. I have one small problem that I can show with some Ruby/Obj-C code. It seems that I have no problem defining classes in Obj-C and overriding an Obj-C method in Ruby if I subclass. What doesn’t work for me is if I override a method from a concrete object. See the code below. The output from the code is

    
    Ruby foo
    Ruby foo
    Ruby foo
    objc foo   <== should also be Ruby foo
    
    Any ideas?
    
    File test.rb ...
    =====================================
    
    require "osx/cocoa" 
    require "Test.bundle" 
    OSX.ns_import :Test
    
    class MyTest < OSX::Test
      def foo
       puts "Ruby foo" 
      end
    
    end
    
    t1 = MyTest.alloc.init
    # this works. Ruby foo prints
    t1.foo
    # this works. Ruby foo prints
    t1.testObjcFoo
    
    t2 = OSX::Test.alloc.init
    def t2.foo
       puts "Ruby foo" 
    end
    
    # this works. Ruby foo prints
    t2.foo
    # doesnt work. obc foo prints
    t2.testObjcFoo
    
    File Test.h ...
    ==============================
    
    #import <Cocoa/Cocoa.h>
    
    @interface Test : NSObject {
    
    }
    
    - (void) foo;
    - (void) testObjcFoo;
    @end
    
    File Test.m ...
    ============================
    
    #import "Test.h" 
    
    @implementation Test
    
    - (void) foo {
       printf("objc foo\n");
    }
    - (void) testObjcFoo {
       [self foo];
    }
    
    void Init_Test(){}
    
    @end