NDK,二进制文件数据读取,在JNI层,通过AAssetManager读取asset内部的资源:
需要头文件的支持
#include <android/asset_manager_jni.h>
#include <android/asset_manager.h>
,首先传个AssetManager到JNI层;
AssetManager assetManager = getAssets();
,将你的数据放到assets文件夹中,然后和对应的文件名字一起,通过JNI Native函数传递到JNI:
readFromAssets(assetManager, "yourdata.bin");
,然后在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<) {
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 ;
}