Sunday, 27 January 2019

Raise events from C to C# (iOS to Unity)

I would like to register for events in Unity and raise those events from C in iOS.

I have the following pattern -

// Unity side register delegate and event handler
private delegate void CallbackDelegate(CBObj data);
public static event CallbackDelegate dataUpdatedEvent;

// for iOS
#if !UNITY_EDITOR && UNITY_IOS
[DllImport("__Internal")]
private static extern void PluginFunction(CallbackDelegate callback);
#endif

public CBObj {
    // marshal C objects to c# objects in the constructor here using the Ptr from C
}
[MonoPInvokeCallback(typeof(CallbackDelegate))]
static void CallbackMethod(CBObj dataPtr)
{
    if (dataUpdatedEvent != null)
    {
        CBObj obj = new CBObj(dataPtr);
        CallbackDelegate(obj);
    }
}

// Unity Usage
private CallbackDelegate evt;
void Start(){
    evt += updateEvent;
}
public void updateEvent(CBObj data){
    // do something with data everytime its called
}

// C code
extern "C" typedef void (*CallBackFuncP) (CBObj dataPtr);
typedef struct
{
    float *data1;
    int *data2;
} CBObj;
extern "C" {
    CallBackFuncP* cb;
    void PluginFunction(CallBackFuncP callback) {
        // store the the callback function pointer
        cb = callback;
    }
}
// raise the event somewhere in code
if (cb != NULL) {
    CBObj *test =  [[CBObj alloc] init];
    cb(test)
}

Would this work? Is this the correct pattern? Is there a better way to do it?

Any pointers to do this are highly appreciated.



from Raise events from C to C# (iOS to Unity)

No comments:

Post a Comment