JNI in C++ to read file to jbyteArray

后端 未结 1 1933
终归单人心
终归单人心 2020-12-21 10:09

I am writing a C++ program in UNIX to generate a shared library which will be called in java using JNI. This C++ program has to read a file in UNIX box then it will have to

相关标签:
1条回答
  • 2020-12-21 10:15

    You don't appear to be setting any byte data to the array. In fact as a jbyte is typedef'd to a char you can directly set your char array in setByteArrayRegion as follows:

    env->SetByteArrayRegion( result, 0, 100, ret );
    

    Edit: Also, assuming that the al[i] should be a1[i] you are doing something very dangerous as you are not allocating space for a1. Basically doing as I suggest above means you can get rid of that entire loop. Also don't forget to delete the C++ Array when you have finished with it (ie copied it into the jByteArray)!

    JNIEXPORT jbyteArray JNICALL Java_com_sp_dll_NativeMethods_getFile
           (JNIEnv *env, jobject obj)
    {
            ifstream fl("/home/rkannan/myFile.txt");
            fl.seekg(0, ios::end );
            size_t len = fl.tellg();
            char *ret = new char[len];
            fl.seekg(0, ios::beg);
            fl.read(ret, len);
            fl.close();
    
            jbyteArray result = env->NewByteArray( len);
            env->SetByteArrayRegion( result, 0, len, (const jbyte*)ret );
    
            delete[] ret;
    
            return result;
    }
    
    0 讨论(0)
提交回复
热议问题