One of Web Biscuit's long-term secret projects is the MidiWrapper
, an object-oriented interface for MIDI. A cornerstone of MIDI operations is the HMIDIOUT
handle, which requires opening before use, and closing when we're done with it.
This can be done in a RAII class. RAII stands for Resource Acquisition is Initialization, not the snappiest acronym in the whole wide world and not that self explanatory. Basically, we use the guarantee that creating an object always calls a constructor and eventually, a destructor. Played smartly, these two opposing calls can give us automatic Open/Close functionality.
Here's our class:
class CMidiOut
{
public:
CMidiOut() {}
~CMidiOut() {}
private:
HMIDIOUT m_hMidiOutHandle;
};
We could add Open
and Close
as public
members, but there really is no need. We don't want to burden the creator of our object with things they might forget to do. So let's do it for them:
class CMidiOut
{
public:
CMidiOut() :
m_hMidiOutHandle(nullptr)
{
midiOutOpen(
&m_hMidiOutHandle, MIDI_MAPPER, NULL, NULL, CALLBACK_NULL); }
~CMidiOut()
{
if(m_hMidiOutHandle != nullptr)
{
midiOutClose(m_hMidiOutHandle);
m_hMidiOutHandle = nullptr;
}
}
private:
HMIDIOUT m_hMidiOutHandle;
};
This is very cute. For a full solution, you'll want an accessor to your handle, and you'll need to prevent or handle copying of your class. These are all exciting subjects we can discuss next time.