一 Unity调用iOS函数 Unity给iOS传值
1.1 C # 代码
# string json 传到原生的
[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)]
private static extern void initSDK(string json);
1.2 oc 代码
# json 为 c#传过来的值
extern "C"{
#endif
void initSDK(const char* json)
{
[[TALVoiceEvaliOSSDK shareInstance] initSDK : json];
}
#if defined(__cplusplus)
}
#endif
1.3 调用 json的形式
initSDK(json.ToString());
二 iOS调用Unity函数 iOS给Unity传值
2.1 通过指针传递,使用 MonoPInvokeCallback
从C#层向C层注册回调函数
2.1 C# 代码
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using AOT;
using UnityEngine;
public class MyScript : MonoBehaviour
{
//c# 调用OC 方法,返回值回调
[DllImport("__Internal")]
private static extern void _calculateSum(int num1, int num2, MyCallbackDelegate callback);
[DllImport("__Internal")]
private static extern void _testResultCallback(string input,ResultCallbackDelegate callback);
[MonoPInvokeCallback(typeof(MyCallbackDelegate))]
private static void MyCallbackFunction(int result)
{
Debug.Log("Received result from native function: " + result);
}
[MonoPInvokeCallback(typeof(ResultCallbackDelegate))]
private static void ResultCallbackFunction(string result)
{
Debug.Log("Received result from native function: ResultCallbackFunction " + result);
}
private delegate void MyCallbackDelegate(int result);
private delegate void ResultCallbackDelegate(string result);
// Start is called before the first frame update
void Start()
{
#if UNITY_IOS
// _calculateSum(1,2,MyCallbackFunction);
_testResultCallback("test",ResultCallbackFunction);
#endif
}
// Update is called once per frame
void Update()
{
}
}
2.2 oc 代码
typedef void(^MyCallback)(int result);
typedef void(^MyCallbackStr)(NSString *result);
@interface MyiOSPlugin : NSObject
+ (void)calculateSum:(int)num1 num2:(int)num2 callback:(MyCallback)callback;
@end
@implementation MyiOSPlugin
+ (void)calculateSum:(int)num1 num2:(int)num2 callback:(MyCallback)callback
{
int sum = num1 + num2;
callback(sum);
}
+ (void)test:(NSString *)inputStr callback:(MyCallbackStr)callback
{
NSLog(@"%@",inputStr);
callback(@"Hello World");}
@end
extern "C" {
void _calculateSum(int num1, int num2, void (*callback)(int))
{
[MyiOSPlugin calculateSum:num1 num2:num2 callback:^(int result) {
callback(result);
}];
}
void _testResultCallback(char *inputStr, void (*callback)(const char *))
{
NSString *str = [NSString stringWithUTF8String:inputStr];
[MyiOSPlugin test:str callback:^(NSString *result) {
callback([result UTF8String]);
}];
}
}
2.2 通过UnitySendMessage 绑定脚本挂载的 Unity Ganme Object 进行通信
2.2.1 C# 代码
//写上在 OC .mm文件中的同名函数
public void callios (string msg)
{
Debug.Log("C#收到:" + msg);
}
// Update is called once per frame
void Update()
{
}
2.2.2 oc 代码
UnitySendMessage 三个参数:
1.脚本挂载的 Unity Ganme Object 名, 根据这个名, 对应的脚本C#代码才能收到iOS发过来的消息.
2.函数名
3.函数参数
*/
[self.object UTF8String] 这个值从C3传过来一定要绑定才能建立oc和c#的绑定关系
UnitySendMessage([self.object UTF8String], "callios", [@"ios消息" UTF8String]);