接着上回的话题继续说明。
2. 简单的C# -> C++ -> Java/ObjC -> C#的异步回调实现
这里以在Native层计算加法,然后将计算结果通过异步回调的方式返回给C#层。首先需要在Unity里声明回调的接口,如下所示:
- using UnityEngine;
- public class UnityCallback : MonoBehaviour {
- public void SumNumResult(string result) {
- print("Result from native = " + result);
- int r = System.Int32.Parse(result);
- TestCallbackManager.sumNumCallback.SendResult(r);
- return;
- }
- }
另外需要在C++层分别给出相应的接口实现,如下所示:
★ Android
C++层代码:
- void SumNum(int v1, int v2){
- __android_log_print(ANDROID_LOG_INFO, "TestUnity", "START ; invoking SumNum(%d, %d)", v1, v2);
- JNIEnv *env = getJNIEnv();
- initJni(env);
- jmethodID mid = env->GetStaticMethodID(jniClass, "SumNum", "(II)V");
- if (env->ExceptionCheck()) {
- env->ExceptionDescribe();
- }
- env->CallStaticVoidMethod(jniClass, mid, v1, v2);
- if (env->ExceptionCheck()) {
- env->ExceptionDescribe();
- }
- __android_log_print(ANDROID_LOG_INFO, "TestUnity", "END ; invoking SumNum():");
- return;
- }
Java层代码:
- public class TestUnity {
- private static final String TAG = "TestUnity";
- // Specify Unity Callback Class
- private static final String UNITYCALLBACK = "UnityCallback";
- // Specify Unity Callback Method
- private static final String SUM_NUM_RESULT = "SumNumResult";
- public static TestUnityActivity activity = null;
- public static void OpenWebView(String url) {
- activity.requestForUrl(url);
- }
- // Mobage API
- public static void SumNum(int v1, int v2) {
- int v = v1 + v2;
- Log.d(TAG, "Result = " + v);
- UnityPlayer.UnitySendMessage(UNITYCALLBACK, SUM_NUM_RESULT, "" + v);
- return;
- }
- }
★ iOS
- #ifdef __cplusplus
- extern "C" {
- #endif
- extern void UnitySendMessage(const char* obj, const char* method, const char* msg);
- void SumNum(int v1, int v2) {
- int v = v1 + v2;
- char s[64];
- sprintf(s, "%d", v);
- UnitySendMessage("UnityCallback", "SumNumResult", s);
- }
- #ifdef __cplusplus
- }
- #endif