John Lam 1997 — 2026

RubyCLR now boxes and unboxes value types

That was a hard problem. RubyCLR now implicitly boxes and unboxes value types correctly. This means that the following test case will now work:

a = ArrayList.new
p = Point.new(3, 4)
a.add(p)
assert_equal 3, a[0].x
assert_equal 4, a[0].y

The code for this has been checked into the trunk. At the heart of the fix is this rather elegant hack that was suggested by Shri Borde.

Instead of attempting to use the box instruction which requires me to know the type being boxed at shim-generation time (which is impossible), instead what I do is:

1) Create a boxed instance of the value type via Activator.CreateInstance 2) Pin that object so that the GC can’t move it 3) Copy the value type into the boxed object 4) Unpin the boxed object

Object^ RubyClr::Marshal::BoxValueType(VALUE object) {
  VALUE klass = rb_class_of(object);
  int   size  = FIX2INT(rb_iv_get(klass, "@value_type_size"));
  Type^ type  = (Type^)Marshal::ToObjectInternal(rb_iv_get(klass, "@clr_type"));

  Object^ boxedInstance = Activator::CreateInstance(type);
  GCHandle handle       = GCHandle::Alloc(boxedInstance, GCHandleType::Pinned);

  try {
    Int32* target = (Int32*)(void*)handle.AddrOfPinnedObject();
    void* source  = (void*)*((Int32*)(object + 16));
    memcpy(target, source, size);
  }
  finally {
    handle.Free();
  }
  return boxedInstance;
}
2 archived reader comments

Jeroen Frijters (2006-06-08)

John, I believe that this is unsafe when the value type contains references (or other value types that contain references), because the GC will not see the appropriate write barrier.

Jeroen Frijters (2006-06-08)

Oh, never mind. I just realized that you’re probably copying values that are already outside of the CLR’s managed heap, so they cannot contain managed references anyway.