I have a C# callback for C++ to invoke as follows:
[MonoPInvokeCallback(typeof(Trace))]
void __internal_trace(IntPtr in_buffer, IntPtr in_length) {
…
this.gameObject.transform.position = XXX;
}
But it always crashes on my iphone with an error about l2CppWrapperException. When I remove the line containing “this”, everything goes well. So I think it is a bug. Any ideas?
Another thing is that when I debug with a single line in my C# callback, with “Debug.Log(this.GetHashcode());”, it’ll crash too, so I think it has something to do with the communication issues between C# and C++
If you show me the real C function, the real c# method, all calls involved, then I can see what’s wrong. I do LOTS of calling from c# → C and C → C# and never get any issues, BUT you have to be very sure you’re marshalling the data correctly or you’re going to get lots of runtime problems.
Edit: But right off the bat this line looks wrong:
int length = in_length.ToInt32();
Since in_length is specified as an IntPtr, should that not be a Int32 or UInt32?
But it’s hard to know without seeing how you’re calling this from C.
And I call it with
UnityInterface::begin_callbacksidx;
If I insert “this.gameObject.transform.position = new Vector4 (0, 0, 0, 0);”, it’ll crash, otherwise not. It’s really strange. Do you develop the code on iOS?
Could it be that because the callback doesn’t happen on the main thread, it crashes because you try to set the position of a gameobject outside the main thread?
You should fire events via the Update() thread or you need to keep the state on the C# side and read/update the Unity state on the Update thread (using appropriate synchronization/locking/etc).
Firing events via the Update thread in Unity is (IMO) the simpler solution.
C#
void Update()
{
MyNativeBindings.update(); //call the native code to update our state.
}
C
extern "C" void update()
{
//
// Do work that'll invoke the c# callbacks.
//
}
But fiddling Unity state on another thread is not going to work.