Unity在Android和iOS中如何调用Native API
本文主要是对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 接口的引用声明是不一样的。本例对应的接口声明如下:
- public class CallNativeAPI {
- #if UNITY_EDITOR
- public static void OpenWebView(string url) {
- return;
- }
- public static void SumNum(int v1, int v2) {
- TestUnityEditor.SumNum(v1, v2);
- return;
- }
- #elif UNITY_IPHONE
- [DllImport ("__Internal")]
- public static extern void OpenWebView(string url);
- [DllImport ("__Internal")]
- public static extern void SumNum(int v1, int v2);
- #elif UNITY_ANDROID
- [DllImport ("libtestunity", CallingConvention = CallingConvention.Cdecl)]
- public static extern void OpenWebView(string url);
- [DllImport ("libtestunity", CallingConvention = CallingConvention.Cdecl)]
- public static extern void SumNum(int v1, int v2);
- #endif
- public static void SumNumForResult(int v1, int v2, CallbackManager.ResultCallback callback) {
- TestCallbackManager.sumNumCallback.SetResultCallBack(new CallbackManager.ResultCallback(callback));
- SumNum(v1, v2);
- return;
- }
- }
- namespace CallbackManager
- {
- public delegate void ResultCallback(int result);
- public class SumNumManager{
- public SumNumManager()
- {
- }
- private ResultCallback resultCallback;
- public void SetResultCallBack(ResultCallback callback)
- {
- resultCallback = callback;
- }
- public void SendResult(int result)
- {
- resultCallback(result);
- }
- }
- }
- public class TestCallbackManager {
- public static CallbackManager.SumNumManager sumNumCallback = new CallbackManager.SumNumManager();
- }
相关推荐
pigsmall 2020-11-19
graseed 2020-10-28
大数据杂谈 2020-09-26
SXIAOYI 2020-09-16
jinhao 2020-09-07
ChinaWin 2020-08-13
mohanzb 2020-08-01
王国平 2020-06-20
yoohsummer 2020-06-01
kangtingting0 2020-05-20
MichelinMessi 2020-02-19
impress 2020-02-20
nicepainkiller 2020-01-25
hfszy0 2013-05-15
lizhenmxcz 2013-05-12
gxyblue 2013-05-11
chenshuixian 2013-06-01
羽化大刀Chrome 2013-05-31
tichangde 2020-01-17