Unity使用native读取streamingasset里文件
需求是,使用native方式,读取apk包里的lua代码,读进c#,做解密
一准备unity工程
public class GameMain : MonoBehaviour { public const string libName = "TGNative"; public Text content; [DllImport(libName)] public static extern int ReadAsset(string fileName, byte[] buffer, int size); // Use this for initialization void Start () { Debug.Log("Start################"); var size = 1024 * 1024; var buffer = new byte[size]; var num = ReadAsset("test.txt", buffer, size); Debug.Log("ReadAsset ################"+ num); if (num > 0 ) { Debug.Log("Read succ"); var str = UTF8Encoding.UTF8.GetString(buffer,0, num); content.text = str; Debug.Log(str); } } // Update is called once per frame void Update () { } }
二unity导出android工程
注意playersetting 里设置包名
三android studio 打开导出的工程
四 添加代码
UnityPlayerActivity里
新增TGNative.java,增加native方法
public native static void InitAssetManager( AssetManager am );
五使用javah生成头文件
javah -d jni -classpath D:\work\ndkread\AssetMgr\AndroidAssetMgr\NativeAssetMgr\build\intermediates\classes\debug;C:\Users\Topjoy\AppData\Local\Android\Sdk\platforms\android-26\android.jar com.topjoy.JniTest.TGNative
六新增NativeUtil.c和Android.mk Applicatioin,mk ,build.bat
build.bat
ndk-build NDK_PROJECT_PATH=. NDK_APPLICATION_MK=Application.mk APP_BUILD_SCRIPT=Android.mk APP_PLATFORM=android-14
NativeUtil.c
// // Created by Topjoy on 2018/12/7. // #include <jni.h> #include <assert.h> #include <string.h> #include <malloc.h> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #include <android/log.h> #include "com_topjoy_JniTest_TGNative.h" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,"Unity",__VA_ARGS__) // 定义LOGD类型 #define LOGW(...) __android_log_print(ANDROID_LOG_WARN,"Unity",__VA_ARGS__) static AAssetManager* mgr = NULL; JNIEXPORT void JNICALL Java_com_topjoy_JniTest_TGNative_InitAssetManager (JNIEnv * env, jclass tis, jobject assetmanager){ mgr = AAssetManager_fromJava(env, assetmanager); } extern int ReadAsset(char* fileName, char* buffer, int size) { if(mgr == NULL) { LOGW( "mgr is null" ); return 0; } AAsset* asset = AAssetManager_open(mgr, fileName, AASSET_MODE_UNKNOWN); if( asset == NULL ) { LOGW( "open asset (%s) failed" , fileName); return 0; } int len = (int)AAsset_getLength(asset); if(len >size) { LOGW("Buffer less than length"); return 0; } int nread = AAsset_read(asset, buffer, size); AAsset_close(asset); if(nread != len) { LOGW("Read num %d not equal length %d", nread, len); return 0; } return nread; }
七运行build.bat 生成so文件
八使用jar命令生成jar文件
@echo off set app=%cd% set debugp=%cd%\build\intermediates\classes\debug set classp=%debugp%\com\topjoy\JniTest cd %classp% pause for %%x in (*) do ( if not "%%x"=="UnityPlayerActivity.class" ( if not "%%x"=="TGNative.class" ( del %%x ) ) ) cd %debugp% jar -cvf class.jar com move class.jar %app%\
九把生成的class.jar 和so文件拷贝进unity工程
十生成apk,拷贝进木木测试
成功!