So here is my problem. We are using a C++ dll (.so) with our unity app. First we register callbacks to delegate using the following signature:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void OnClientStateChange(int oldState, int newState);
public OnClientStateChange onClientStateChange;
And I pass those to the unmanaged side with: Marshal.GetFunctionPointerForDelegate(onClientStateChange)
In unmanaged my signature is
typedef void CDECL tClientStateChange(int oldState, int newState);
tClientStateChange* cb_clientStateChange;
where CDECL is defined to nothing under android.
Now on the unmanaged side, we are using multiple threads, and one of those is calling my callback. Everything works fine, except one thing… a few seconds later my app crashes.
This issue only occurs on android (everything is fine in windows). I tried emptying the callback (basically calling an empty function) and I still get that crash a few seconds later.
I am nowhere near an expert on CLI and C++/C# interactions. I read as much as I could and ended up reading that in multi-threaded environments I need to call mono_thread_attach on any new thread before invoking managed code. I have no idea if this is accurate or if I misunderstood, nor how or where to find that function (and google has very few answers)
My guess is that the call to managed callback somehow messes with my memory, and creates a crash later down the line (not calling the callback, no crash. calling it, even with an empty function as callback, crash). I also tried using the stdcall calling convention, with no luck.
If anyone has any idea I would really appreciate. Unfortunately I can’t provide a code example as it is a rather big and proprietary project. My adb log is pretty much worthless, and always indicate an error in libmono. I am not proficient enough with assembly to make any sense of an objdump and anyways, the crash happens when I am randomly pressing buttons in the app later on, and nowhere near the moment when I make my call to the callback. (those buttons only show/hide menus, no funky stuff in there)