I am trying to do c#/rust interop, and calling rust from c# is ok by far, but calling c# from rust would lead to a crash.I just pass a struct with delegate field to rust, and call the delegate from rust.
C# code:
[StructLayout(LayoutKind.Sequential)]
public class UnityBinding
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate void Test();
//[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
//delegate void UnityDebugLog(IntPtr data, int length);
private Test test;
//private UnityDebugLog debugLog;
//[MonoPInvokeCallback(typeof(UnityDebugLog))]
public static void DebugLog(IntPtr data, int length)
{
Debug.Log("debug log called");
//var message = Marshal.PtrToStringAuto(data, length);
//Debug.Log(message);
}
[MonoPInvokeCallbackAttribute(typeof(Test))]
public static void MyTest()
{
Debug.Log("Test called");
}
public static UnityBinding Create()
{
return new UnityBinding
{
test = MyTest,
//debugLog = DebugLog,
};
}
}
Rust code:
#[repr(C)]
pub struct UnityBinding {
pub(crate) test: extern "C" fn(),
//pub(crate) debug_log: extern "C" fn(*const c_void, i32),
}
pub extern "C" fn init_unity_engine(binding: UnityBinding) {
println!("before debug_log");
(binding.test)();
println!("after debug_log");
}
I can't figure out what's wrong here, I really need some help, thanks.