NDK,在JNI層使用AssetManager讀取文件


NDK,二進制文件數據讀取,在JNI層,通過AAssetManager讀取asset內部的資源:

  需要頭文件的支持
  #include <android/asset_manager_jni.h>
  #include <android/asset_manager.h>

1,首先傳個AssetManager到JNI層;
    AssetManager assetManager = getAssets();
2,將你的數據放到assets文件夾中,然后和對應的文件名字一起,通過JNI Native函數傳遞到JNI:
    readFromAssets(assetManager, "yourdata.bin");
3,然后在JNI的Native實現函數中讀取:(也可直接在對應的C函數調用,調用方法類似fopen,fread)

JNIEXPORT  jstring JNICALL Java_com_lib_MyLib_readFromAssets(JNIEnv* env, jclass clazz,
        jobject assetManager, jstring dataFileName) {
        
    AAssetManager* mManeger = AAssetManager_fromJava(env, assetManager);
    jboolean iscopy;
    const char *dataFile = env->GetStringUTFChars(dataFileName, &iscopy);
    
    int c = dataRead(mManeger, dataFile);  //call the C function

    env->ReleaseStringUTFChars(dataFileName, dataFile);
    
    jstring resultStr;
    resultStr = env->NewStringUTF("success");
    return resultStr;
}
int dataRead(AAssetManager* mManeger, const char *dataFile){

    AAsset* dataAsset = AAssetManager_open(mManeger, dataFile, AASSET_MODE_UNKNOWN);//get file read AAsset
    off_t dataBufferSize = AAsset_getLength(dataAsset);
    
    int num = dataBufferSize/sizeof(float);  
    
    //float *data = (float*) malloc(num * sizeof(float));  //allocate the data, the same with the later line
    float *data = (float*) malloc(dataBufferSize);
    
    int numBytesRead = AAsset_read(dataAsset, data, dataBufferSize);  //begin to read data once time
  //note: numBytesRead is the total bytes, then num = dataBufferSize/sizeof(float) = numBytesRead/sizeof(float)
if (numBytesRead<0) { LOGI("read data failed"); } else{ LOGI("numBytesRead: %d", numBytesRead); } //int numBytesRead; //for (int i = 0; i < num; i++) { // numBytesRead = AAsset_read(dataAsset, (char*) (&data[i]), sizeof(float)); //or read the data one by one // if (numBytesRead<0) { // LOGI("read data failed"); // } // else{ // LOGI("numBytesRead: %d", numBytesRead); // } //} AAsset_close(dataAsset); free(data); return 0; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM