Hello, i’m using microsoft onnxruntime with unity. When i build for android with mono, it works great but if i change it to il2cpp, following error happens:
MarshalDirectiveException: Cannot marshal P/Invoke call through delegate of type '.DOrtGetApi'
at System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointerInternal (System.IntPtr ptr, System.Type t) [0x00000] in <00000000000000000000000000000000>:0
at System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer (System.IntPtr ptr, System.Type t) [0x00000] in <00000000000000000000000000000000>:0
at Microsoft.ML.OnnxRuntime.NativeMethods..cctor () [0x00000] in <00000000000000000000000000000000>:0
at Microsoft.ML.OnnxRuntime.SessionOptions..ctor () [0x00000] in <00000000000000000000000000000000>:0
at Microsoft.ML.OnnxRuntime.InferenceSession..ctor (System.String modelPath) [0x00000] in <00000000000000000000000000000000>:0
at ML.Predict (UnityEngine.Texture2D framecam) [0x00000] in <00000000000000000000000000000000>:0
at CameraFeed.Update () [0x00000] in <00000000000000000000000000000000>:0
Rethrow as TypeInitializationException: The type initializer for 'Microsoft.ML.Onnx
I’d have to know a bit more about this type .DOrtGetApi to be provide more details. Although Mono is pretty permissive on delegate marshaling, where IL2CPP sticks to the letter of the law and tries to follow all of the marshaling rules.
So it may be that this just happens to work on Mono when it should not work. But this also could be a bug in IL2CPP, where some marshaling case that should be handled is not handled correctly.
Possibly with the error message saying ‘Cannot marshal P/Invoke call through delegate’ it’s the subsequent usage where a function pointer within that struct is called.
We’ve now corrected this issue internally, thanks for reporting it! As it turns out, IL2CPP was too aggressive in not allowing marshaling for delegates with by reference return types. I’ve lifted that restriction in the IL2CPP code, and we should get it into Unity releases soon.