John Lam 1997 — 2026

Adding CIL instance methods to Ruby classes

I did a pretty major refactoring against the code that I shipped last night and streamlined the way data types were marshaled between Ruby and the CLR. Here’s a more concrete example of an add method implemented entirely in CIL that is attached to a Ruby Calc class:

class MarshalParametersToRubyTests < Test::Unit::TestCase
include RbDynamicMethod
class Calc
end
def test_add
create_ruby_instance_method(Calc, 'add') do
declare  'Int32', 'x'
declare  'Int32', 'y'
ldarg_1
ldind_i4
call     'static Marshal.ToInt32(UInt32)'
stloc_s  'x'
ldarg_1
ldc_i4_4
add
ldind_i4
call     'static Marshal.ToInt32(UInt32)'
stloc_s  'y'
ldloc_s  'x'
ldloc_s  'y'
add
call     'static Marshal.ToRubyFixnum(Int32)'
ret
end
assert_equal 7, Calc.new.add(3, 4)
end
end
2 archived reader comments

Dave Lee (2005/12/07)

I’m not sure how far you want to push the limits of *_missing magic, but you could probably have a DSL that is string-free and a declaration-free, or close to it. I’m pretty sure it’d be possible to make your example into: Generator::Calc.new.add(Int32 x, Int32 y) do ldarg_1 ldind_i4 call { static Marshal.ToInt32(UInt32) } stloc_s x ldarg_1 ldc_i4_4 add ldind_i4 call { static Marshal.ToInt32(UInt32) } stloc_s y ldloc_s x ldloc_s y add call { static Marshal.ToRubyFixnum(Int32) } ret end

John Lam (2005/12/07)

Hey Dave - it’s good to see you around here again. You’re more than welcome to extend this thing if you want - it’s pretty usable as-is for the real goal of this effort which is a rewrite of my bridge in mostly Ruby. Why don’t you send me a mail with your current coordinates (still doing the basketball thing?) there’s some stuff I’d like to chat with you about …