T.N.
T.N.

Reputation: 87

C++/CLI Wrapper: callback gets fired after the objects containing the memberfunction is deleted

My problem is, that I have a callback which gets called after my mainthread deleted the object that contained the memberfunction the callback wants to call. Therefore, my program crashes. Is there any way, to pretend the crash? I am not able to change the flow of my mainthread.

My main thread starts a new thread for a specific task and waits in an dialog. If the user presses cancel before the task (bluetooth scan) is done, the mainthread continues and deletes the object that is needed for the callback, to call.

typedef std::tr1::function<void __cdecl ()>* callback_function;

callback_function m_bluetoothScan  = //Some function in native C++

// The c++/cli callback
void Connection::BluetoothScanCallback(IAsyncResult^ ar)
{
  if (m_bluetoothScan != nullptr)
  {
    (*m_bluetoothScan)(); // The native c++ member function
  }
}

UPDATE:

Like @xMRi pointed out, I had to unregister my callback inside my destructor. What I did was, setting my callback_function to nullptr and inside my BluetoothScanCallback function on the CLI side, I check if m_bluetoothScan is nullptr and thus don't try to call my callback. Thanks a lot!

Upvotes: 0

Views: 81

Answers (1)

xMRi
xMRi

Reputation: 15365

When the object is deleted it should be obvious that you have to take care about all references that uses the object. So from my point of view you have also remove any reference to it.

This means: Deleting the object requires unregistering the callback.

A good way would be using smart pointers to the object, so was long as there is a object reference, the object will not be deleted.

You can also use strong and weak pointer. So storing a weak pointer for the callback function and a strong pointer for the object. So the C++/CLI part ist capable to distinguish that there is no longer need to call the callback function.

Upvotes: 2

Related Questions