Opening and and closing MidiOutput

If I store an opened MidiOutput in a field for later use and start its background thread, when I later access the MidiOutput field to stop the background thread, the program crashes with an access violation.

The following demo class reproduces the problem. I have the class’s startMidiOutTester() and stopMidiOutTester() methods assigned to Start and Stop buttons respectively in the GUI.

#pragma once
#include <JuceHeader.h>
using namespace juce;

class MidiOutTester : HighResolutionTimer {
public:
  void startMidiOutTester() {
    // Put the name of an available MIDI output device here.
    const String midiOutDeviceName("02. Internal MIDI");
    midiOutput.reset(MidiOutput::openDevice(midiOutDeviceName).get());
    midiOutput->startBackgroundThread();
    startTimer(1000);
  }
  
  void stopMidiOutTester() {
    stopTimer();
    // Crashes with access violation
    midiOutput->stopBackgroundThread(); 
  }

private:  
  std::unique_ptr<MidiOutput> midiOutput;
  
  void hiResTimerCallback() override {
    DBG("Will eventually want to do stuff with midiOutput here.");
  }
};

MidiOutput::openDevice() returns a unique_ptr, you need to call unique_ptr.release() if you want to take ownership of the object.

midiOutput.reset(MidiOutput::openDevice(midiOutDeviceName).release());

Or

midiOutput = MidiOutput::openDevice(midiOutDeviceName);

Is probably what you want.

Thanks, @oli1! Those both work, with the second of course preferred.