Unity在Android和iOS中如何調用Native API

來源:互聯網
上載者:User

標籤:

本文主要是對unity中如何在Android和iOS中調用Native API進行介紹。

首先unity支援在C#中調用C++ dll,這樣可以在Android和iOS中提供C++介面在unity中調用。利用這一特性,可以擴充unity的功能。例如整合和調用第三方庫。同時為了滿足對unity介面的一致性,可以考慮在android和iOS上提供相同的介面供C#調用。

這裡列舉以下兩個例子。

1. 1. 以彈出一個覆蓋部分螢幕的webview為例來說明如何從C#調用Native介面。

2. 2. 簡單的C# -> C++ -> Java/ObjC -> C#的非同步回調實現(會在下一期中給出實現)

由於android和iOS平台載入庫的方式不同(android為動態載入,iOS為靜態載入),在C#中針對不同平台對dll 介面的引用聲明是不一樣的。本例對應的介面聲明如下:

 1 public class CallNativeAPI {  2       3 #if UNITY_EDITOR  4     public static void OpenWebView(string url) {  5         return;  6     }  7       8     public static void SumNum(int v1, int v2) {  9         TestUnityEditor.SumNum(v1, v2); 10          11         return; 12     } 13 #elif UNITY_IPHONE 14     [DllImport ("__Internal")] 15     public static extern void OpenWebView(string url); 16     [DllImport ("__Internal")] 17     public static extern void SumNum(int v1, int v2);    18 #elif UNITY_ANDROID 19     [DllImport ("libtestunity", CallingConvention = CallingConvention.Cdecl)] 20     public static extern void OpenWebView(string url); 21     [DllImport ("libtestunity", CallingConvention = CallingConvention.Cdecl)] 22     public static extern void SumNum(int v1, int v2); 23 #endif   24      25     public static void SumNumForResult(int v1, int v2, CallbackManager.ResultCallback callback) { 26          27         TestCallbackManager.sumNumCallback.SetResultCallBack(new CallbackManager.ResultCallback(callback)); 28  29         SumNum(v1, v2); 30  31         return; 32     } 33 } 34  35 namespace CallbackManager 36 { 37     public delegate void ResultCallback(int result); 38      39     public class SumNumManager{ 40         public SumNumManager() 41         { 42         } 43          44         private ResultCallback resultCallback; 45  46         public void SetResultCallBack(ResultCallback callback) 47         { 48             resultCallback = callback; 49         } 50              51         public void SendResult(int result) 52         { 53             resultCallback(result); 54         } 55     } 56 } 57  58 public class TestCallbackManager { 59  60     public static CallbackManager.SumNumManager sumNumCallback = new CallbackManager.SumNumManager(); 61      62 }

 

轉載至:

    Unity在Android和iOS中如何調用Native API

Unity在Android和iOS中如何調用Native API

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.