Jump to content
Happy Holidays! Limited Staff Responses: 1/20 - 1/31 ×

Unity il2cpp and callbacks


C3D
 Share

Recommended Posts

Hi,

I've been following the callback example @Corvuswrote here a while ago (link) and ran into some issues when using Unity's IL2CPP scripting backend instead of Mono. The editor is fine, but here are the errors I saw in a build:

il2cpp, non static callback
NotSupportedException: IL2CPP does not support marshaling delegates that point to instance methods to native code. The method we're attempting to marshal is: CallbackExample::EyeCallback

il2cpp, static callback
NotSupportedException: To marshal a managed method, please add an attribute named 'MonoPInvokeCallback' to the method definition. The method we're attempting to marshal is: CallbackExample::EyeCallback

The solution was to make the EyeCallback static and add the MonoPInvokeCallback attribute to the method. Easy enough to fix, the main difficulty was figuring out what was different between editor and build.

    //other code
    
    internal class MonoPInvokeCallbackAttribute : System.Attribute
    {
        public MonoPInvokeCallbackAttribute() { }
    }

    private static EyeData eyeData = new EyeData();

    [MonoPInvokeCallback]
    private static void EyeCallback(ref EyeData eye_data)
    {
        eyeData = eye_data;
        // do stuff with eyeData..
    }

So my question: is this the best way to deal with this?

And for my own curiosity - I'm assuming Unity is removing this method in the 'stripping assemblies' step before changing the il into cpp. Why isn't it stripping this attribute too?

Thanks

Link to comment
Share on other sites

@C3D Yes, the callback should probably be static anyways and adding the "MonoPInvokeCallback" attribute will be required for IL2CPP scripting backend support. I tested with stripping level on high and had no issues with the static callback & attribute.

Also, if you are having issues between Unity editor and builds it can be helpful to check "Development Build" in the Unity Build Settings to attach the log console and easily see errors.

Let us know if you have any further feedback or errors.

Link to comment
Share on other sites

  • 1 year later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...