This project is read-only.
Boxing / Unboxing

Boxing is the ability to move a structure from the stack to the heap, and unboxing is the other way around.
.NET manages this in a transparent manner. One still has to cast when unboxing the structure.

Example of C# boxing:

object Test1(int a)
{
    return (a);
}


Generated code in C++:

::System::Object * CrossNetUnitTest::Various::TestBox::Test1(::System::Int32 a)
{
    return (::CrossNetRuntime::Box<::System::Object>(a));
}


Example of C# unboxing:

int Test4(object o)
{
    return (int)(o);
}


Generated code in C++:

::System::Int32 CrossNetUnitTest::Various::TestBox::Test4(::System::Object * o)
{
    return ((::CrossNetRuntime::Unbox<::CrossNetRuntime::__BaseTypeWrapper__<::System::Int32>::BoxeableType >(o)));
}


When boxing, we use the templated class CrossNetRuntime::BoxedObject (hidden by the CrossNetRuntime::Box templated function). A BoxedObject is a standard object with the structure as member.
At construction, it duplicates the content of the passed structure and initialize correctly the interface map.
All the standard Object functions are actually forwarded to the corresponding structure.
For primitive types, we are using the BaseTypeWrapper that contains all the necessary features.

Note that a boxed object can be converted to a Sysstem.Object, any of the interfaces that the structure implements or unboxed to the structure.
During both boxing / unboxing, we are actually duplicating the structure, so they represent different objects in memory.

Last edited Sep 7, 2007 at 10:24 PM by OlivierNallet, version 1

Comments

No comments yet.