Monday, January 6, 2014

Defining Callback in Unity3D C Plugin and C# Script

Lately I am working on one Unity3d Game and for using some platform specific feature I required to create a native plugin in C.

I am not done with creating complete plug-in yet and will post more about creating plug-in in separate post. But while I am working on plug-in creation for Unity3D, I required to use callback or notification from C code to Unity c# script.

Following is How we can use callback between C based plugin and C# unity script.

Following is definition of callback function/function pointer which will call C# function.
typedef void ( *CALLBACK )( const char* );
static CALLBACK cb; 
This is how we are going to set and use defined callback function.
void runEventLoop(CALLBACK test) {
    cb = test; 
    cb("hello plugin...");
}
Following is complete C code.
extern "C"
{ 
 typedef void ( *CALLBACK )( const char* );
 static CALLBACK cb;
 
 void runEventLoop(CALLBACK test) {
  cb = test;
  cb("hello plugin...");
 }
}

Now we have required C code for sending notification or providing the callback. But we need to create C# script, which define function which will be called on notification from plug-in.

Following is C# script.
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;

public class PluginImport : MonoBehaviour {

 public delegate void callbackDelegate( string str );

 [DllImport ("Plugin")]
 private static extern void runEventLoop(callbackDelegate test);

 void callback(string str) {
    Debug.Log(str);
 }

 void Start () { 
    runEventLoop(new callbackDelegate( this.callback ));
 }
}

This should be enough to get notification from C code to C# script.

No comments:

Post a Comment