C++ -> C++/CLI How to pass native member function as callback to managed code

0

I have a native callback function in C++, let's say something like this:

void ::CallbackFunction(void)
{
  // Do nothing
}

Now I have another native function:

void ::SomeNativeFunction(void)
{
  m_callback = std::tr1::bind(&::CallbackFunction, m_Tcy); // save in m_callback (std::tr1::function<void()>)
  m_Tcy->SomeManagedFunction(&m_callback);
}

Alright, so now I called a managed function and gave this function a native c++ function. I then have another project, a C++/CLI one, which exports a native class to provide my native app functionality from the .NET world. Let's look into the managed code:

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

callback_function m_nativCallback;

void ::SomeManagedFunction(callback_function callback)
{
  m_nativCallback = callback;
  // Does some stuff that triggers SomeManagedCallback
}

void ::SomeManagedCallback(IAsyncResult^ ar)
{
  (*m_nativCallback)();
}

Now, if I debug this, everything works fine, but after leaving the callback function (inside managed class) Visual Studio (VS2010) does not respond anymore and crashes. Sometimes I managed to close the app and VS restores itself and shows me these errors:

First-chance exception at 0x00007ffb2b59dd60 in *.exe: 0xC0000005: Access violation at location 0x00007ffb2b59dd60.
Unhandled exception at 0x00007ffb2b59dd60 in *.exe: 0xC000041D: Exception during a user callback.

It's very hard to debug, so I am having serious problems to find out what is throwing these exceptions. Can anybody help me?

Much appreciated!

c++
asked on Stack Overflow Oct 25, 2018 by T.N. • edited Oct 25, 2018 by T.N.

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0