Test.mm
char* TestMakeCString(NSString *str) { const char* string = [str UTF8String]; if (string == NULL) { return NULL; } char* res = (char*)malloc(strlen(string) + 1); strcpy(res, string); return res; }
extern "C"{ typedef void (*TestCallback)(const char*eventName); TestCallback _myCallback; void _TestInit(TestCallback callback){ _myCallback=callback; } } @implementation Test -(void) test{ _myCallback(TestMakeCString(@"complete")); } @end
Test.cs
using System.Runtime.InteropServices; public class Test{ public delegate void EventHandler(string eventName, string msg); public event EventHandler callbackHandler; internal delegate void TestCallBack(string eventName); [DllImport("__Internal")] private static extern void _TestInit(TestCallBack callback); [MonoPInvokeCallback(typeof(TestCallBack))] public static void onCallBack(string eventName){ if(eventName=="complete"){ //do something if(callbackHandler!=null)callbackHandler(eventName,"HIJK"); } } public static Test _instance; public static Test getInstance(){ if(_instance==null){ _instance=new Test(); } return _instance; } //初始接口 public void init(){ _TestInit(onCallBack); } }
demo:
Test test=Test.getInstance() test.init(); test.callbackHandler+=handler; void handler(string eventName,string msg){ //do something }