1.写NativeCode.c文件
#include <stdio.h>
//#include <string>
#include <android/log.h>
#define DEBUG 1 //日志开关,1为开,其它为关
#if(DEBUG==1)
#define LOG_TAG "XHSJ_JNI"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,TAG,__VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#else
#define LOGV(...) NULL
#define LOGD(...) NULL
#define LOGI(...) NULL
#define LOGE(...) NULL
#endif
typedef struct Parameter {
int a;
int b;
} Param;
typedef void (*CallBack)(Param* p);
void TestFunc(CallBack cb){
Param p;
p.a = 10;
p.b = 20;
LOGE("a = %d ; b = %d\n",p.a,p.b);
cb(&p);
}
2.编译为libnative.so文件
如何编译参考https://blog.csdn.net/yhx956058885/article/details/105654224
3.unity调用,绑定button调用Click_TestFunc
using UnityEngine;
using System.Runtime.InteropServices;
using System;
using AOT;
public class NewBehaviourScript : MonoBehaviour {
[StructLayout(LayoutKind.Sequential)]
struct Parameter
{
public int a;
public int b;
}
delegate void CallBack(IntPtr param);
[DllImport("native")]
static extern void TestFunc(CallBack cb);
[MonoPInvokeCallback(typeof(CallBack))]
static void CallBackFunc(IntPtr param)
{
Parameter p = (Parameter)Marshal.PtrToStructure(param, typeof(Parameter));
Debug.Log("a:" + p.a + " b:" + p.b);
}
public void Click_TestFunc()
{
TestFunc(CallBackFunc);
}
}
4.logcat查看打印信息