一 调用方法一
1.1 Unity代码-Unity调方法传参,有返回值
cs
[DllImport("__Internal")]
// 给iOS传string参数,有返回值,返回值通过iOS的return方法返回给Unity
private static extern string getIPv6(string mHost, string mPort)
1.2 iOS代码-iOS通过return方法,将值返回给Unity
cpp
/**
获取IPv6的值,并返回给Unity
@param mHost 主机名
@param mPort 端口号
@return IPv6值
*/
extern "C" const char * getIPv6(const char *mHost, const char *mPort)
{
return mHost;
}
1.3 注意空间分配(上面的写法会报如下错误)
bash
skins(2509,0x1a8e5cb40) malloc: *** error for object 0x16fdc9114: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
1.4 修改错误后正确代码
cpp
/**
获取IPv6的值,并返回给Unity
@param mHost 主机名
@param mPort 端口号
@return IPv6值
*/
extern "C" const char * getIPv6(const char *mHost, const char *mPort)
{
// strdup(const char *__s1) 复制mHost字符串,通过Malloc()进行空间分配
return strdup(mHost);
}
1.5 如果Unity传参为int类型,可以使用return mHost方法
unity代码
cs
[DllImport("__Internal")]
// 给iOS传int参数,无返回值,返回值通过iOS的return方法返回给Unity
private static extern int setMyInt(int date);
ios代码
cpp
// 返回int值
extern "C" int setMyInt(int date)
{
return date;
}
1.5 总结
1:如果Unity传参为string类型,不执行strdup()方法而使用return mHost方法,导致mHost没有分配内存空间而报错
2:Unity方法中参数的变量名为date,在iOS中的extern "C" int setMyInt(int date)方法中设置的参数变量名可以与Unity的相同,设置为date,也可以是a、b、c等自定义参数变量,但是为了代码规范,尽量和Unity参数保持一致.
3:调用DllImport("")方法,需要引入命名空间:
using System.Runtime.InteropServices;
4:extern "C"修饰的变量和函数是按照C语言方式编译和连接的
二 Unity调方法传参,无返回值
2.1 unity代码
cs
// 传数据给iOS
[DllImport("__Internal")]
// 给iOS传string参数,无返回值,返回值通过iOS的UnitySendMessage方法返回给Unity
private static extern void setDate(string date);
// 接收iOS的数据
public void GetDate(string date)
{
}
2.2 ios代码
cpp
/**
返回Unity日期
@param date 日期
@return 无返回值
*/
extern "C" void setDate(const char *date)
{
/**
发送数据给Unity
@param obj 模型名
@param method Unity接收iOS数据的方法名
@param msg 传给Unity的数据
UnitySendMessage(const char* obj, const char* method, const char* msg);
*/
UnitySendMessage("PublicGameObject", "GetDate", date);
}
2.3
iOS通过UnitySendMessage方法返回数据给Unity时,需要传正确的date值,如果UnitySendMessage方法中的第三个参数不是将date作为参数,而是自定义的NSString类,需要做类型转换(Unity中的字符串为string,OC中的字符串为NSString)如下代码
bashextern "C" void setDate(const char *date) { NSString *dateStr = @"Hello Word"; UnitySendMessage("PublicGameObject", "GetDate", [dateStr UTF8String]); }
三 完整代码
3.1 ios 代码
cpp
//
// UserAgent.m
// UnityFramework
//
// Created by lxj on 2024/3/25.
//
#import "UserAgent.h"
#import <WebKit/WebKit.h>
#import "SensorsAnalyticsSDK.h"
#pragma mark - Unity 回调函数
//初始化回调
static void(*GetUserAgentCallback)(const char *);
@implementation UserAgent
#pragma mark - 供Unity调用的函数接口
#if defined(__cplusplus)
extern "C"{
#endif
void getUA(void(*getUserAgentCallback)(const char *)){
GetUserAgentCallback = getUserAgentCallback;
[[UserAgent GetInstance] GetUserUIWebViewAgent];
}
const char * getAnonymousId(){
const char * anonymousId = [[[SensorsAnalyticsSDK sharedInstance] anonymousId] UTF8String];
return strdup(anonymousId);
}
const char * getDistinctId(){
const char * distinctId = [[[SensorsAnalyticsSDK sharedInstance] distinctId] UTF8String];
return strdup(distinctId);
}
#if defined(__cplusplus)
}
#endif
-(void)GetUserUIWebViewAgent{
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero];
NSString * result = [webView valueForKey:@"userAgent"];
if(GetUserAgentCallback){
GetUserAgentCallback([result UTF8String]);
NSLog(@"iOS 获取到的当前设备的userAgent为 ===%@",result);
GetUserAgentCallback = nil;
}
}
UserAgent* instanceUA = nil;
+(UserAgent*)GetInstance
{
NSLog(@"DoInit");
if(instanceUA == nil)
{
instanceUA = [[UserAgent alloc] init];
}
return instanceUA;
}
@end
3.2 unity代码
cs
#if UNITY_IOS
using System;
using System.Runtime.InteropServices;
using AOT;
using Bao.Debug;
using Bao.Stage;
using UnityEngine;
namespace Code.SDK.DeviceId.iOS {
public class IOSDeviceIdClient: IDeviceIdClient {
protected static Action<string> GetUAResultCallback;
private const string INTERNAME_NAME = "__Internal";
[DllImport(INTERNAME_NAME, CallingConvention = CallingConvention.Cdecl)]
private static extern void getUA(GetUACallbackDelegate callback);
[DllImport(INTERNAME_NAME, CallingConvention = CallingConvention.Cdecl)]
private static extern string getAnonymousId();
[DllImport(INTERNAME_NAME, CallingConvention = CallingConvention.Cdecl)]
private static extern string getDistinctId();
public void GetOAID(Action<string> callback) {
callback?.Invoke(null);
}
public void GetUA(Action<string> callback)
{
var ua = PlayerPrefs.GetString(DeviceIdConstants.KEY_ATTRIBUTE_UA);
LogFile.get.Log("ios本地存储UA值为 == " + ua);
if (string.IsNullOrEmpty(ua))
{
GetUAResultCallback = callback;
getUA(GetUACallback);
}
else
{
callback?.Invoke(ua);
}
}
/// <summary>
/// getUA
/// </summary>
private delegate void GetUACallbackDelegate(string ua);
/// <summary>
/// getUA回调
/// </summary>
/// <param name="ua"></param>
[MonoPInvokeCallback(typeof(GetUACallbackDelegate))]
private static void GetUACallback(string ua)
{
LogFile.get.Log("ios从原生获取UA值为 == " + ua);
PlayerPrefs.SetString(DeviceIdConstants.KEY_ATTRIBUTE_UA, ua);
PlayerPrefs.Save();
if (GetUAResultCallback != null)
{
GetUAResultCallback(ua);
GetUAResultCallback = null;
}
}
public string GetAndroidId() {
return null;
}
public string GetAnonymousId() {
string anonymousId = getAnonymousId();
LogFile.get.Log("ios神策设备id == " + anonymousId);
return anonymousId;
}
public string GetDistinctId()
{
string distinctId = getDistinctId();
LogFile.get.Log("ios神神策id == " + distinctId);
return distinctId;
}
}
}
#endif