From Nish.
//code starts here
namespace msclr
{
namespace interop
{
template<> ref class context_node<System::Drawing::Font^, HFONT> : public context_node_base
{
private:
System::Drawing::Font^ _font;
public:
context_node(System::Drawing::Font^% to, HFONT from)
{
to = _font = System::Drawing::Font::FromHfont((IntPtr)from);
}
~context_node()
{
this->!context_node();
}
protected:
!context_node()
{
delete _font;
}
};
template<> ref class context_node<HFONT, System::Drawing::Font^> : public context_node_base
{
private:
HFONT _hFont;
public:
context_node(HFONT& to, System::Drawing::Font^ from)
{
to = _hFont = (HFONT)from->ToHfont().ToPointer();
}
~context_node()
{
this->!context_node();
}
protected:
!context_node()
{
DeleteObject(_hFont);
}
};
}
}//code ends here
Wow. Our first use of a context. Instead of writing a function that implements a specialization of the template function, you write a class that implements a specialization of the template class. Since it's a class, it can have member variables, which you clean up when the context goes out of scope.
Here's how you might use it:
HFONT hFont = CreateSampleFont();
marshal_context context;
System::Drawing::Font^ font =
context.marshal_as<System::Drawing::Font^>(hFont);
HFONT hFontCopy = context.marshal_as<HFONT>(font);
DeleteObject(hFont);
Kate