From 7338b8f22d06c04b3fe7b96952ac5591838b2797 Mon Sep 17 00:00:00 2001 From: Stephen Sinclair Date: Thu, 2 Mar 2017 15:40:28 -0300 Subject: [PATCH] C api: track CallbackProxyUserData and delete it Fixes #104. --- rtmidi_c.cpp | 39 +++++++++++++++++++++++---------------- rtmidi_c.h | 1 + 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/rtmidi_c.cpp b/rtmidi_c.cpp index 5148a718..3b6577c3 100644 --- a/rtmidi_c.cpp +++ b/rtmidi_c.cpp @@ -3,6 +3,17 @@ #include "rtmidi_c.h" #include "RtMidi.h" +class CallbackProxyUserData +{ + public: + CallbackProxyUserData (RtMidiCCallback cCallback, void *userData) + : c_callback (cCallback), user_data (userData) + { + } + RtMidiCCallback c_callback; + void *user_data; +}; + /* misc */ int rtmidi_sizeof_rtmidi_api () { @@ -133,11 +144,13 @@ RtMidiInPtr rtmidi_in_create (enum RtMidiApi api, const char *clientName, unsign RtMidiIn* rIn = new RtMidiIn ((RtMidi::Api) api, name, queueSizeLimit); wrp->ptr = (void*) rIn; + wrp->data = 0; wrp->ok = true; wrp->msg = ""; } catch (const RtMidiError & err) { - wrp->ptr = 0; + wrp->ptr = 0; + wrp->data = 0; wrp->ok = false; wrp->msg = err.what (); } @@ -147,6 +160,8 @@ RtMidiInPtr rtmidi_in_create (enum RtMidiApi api, const char *clientName, unsign void rtmidi_in_free (RtMidiInPtr device) { + if (device->data) + delete (CallbackProxyUserData*) device->data; delete (RtMidiIn*) device->ptr; delete device; } @@ -164,17 +179,7 @@ enum RtMidiApi rtmidi_in_get_current_api (RtMidiPtr device) } } -class CallbackProxyUserData -{ - public: - CallbackProxyUserData (RtMidiCCallback cCallback, void *userData) - : c_callback (cCallback), user_data (userData) - { - } - RtMidiCCallback c_callback; - void *user_data; -}; - +static void callback_proxy (double timeStamp, std::vector *message, void *userData) { CallbackProxyUserData* data = reinterpret_cast (userData); @@ -183,13 +188,14 @@ void callback_proxy (double timeStamp, std::vector *message, void void rtmidi_in_set_callback (RtMidiInPtr device, RtMidiCCallback callback, void *userData) { + device->data = (void*) new CallbackProxyUserData (callback, userData); try { - void *data = (void *) new CallbackProxyUserData (callback, userData); - ((RtMidiIn*) device->ptr)->setCallback (callback_proxy, data); - + ((RtMidiIn*) device->ptr)->setCallback (callback_proxy, device->data); } catch (const RtMidiError & err) { device->ok = false; device->msg = err.what (); + delete (CallbackProxyUserData*) device->data; + device->data = 0; } } @@ -197,7 +203,8 @@ void rtmidi_in_cancel_callback (RtMidiInPtr device) { try { ((RtMidiIn*) device->ptr)->cancelCallback (); - + delete (CallbackProxyUserData*) device->data; + device->data = 0; } catch (const RtMidiError & err) { device->ok = false; device->msg = err.what (); diff --git a/rtmidi_c.h b/rtmidi_c.h index 1434763f..01b1bfc5 100644 --- a/rtmidi_c.h +++ b/rtmidi_c.h @@ -15,6 +15,7 @@ extern "C" { struct RtMidiWrapper { void* ptr; + void* data; bool ok; const char* msg; };