Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy data from char buffer into jbyteArray and return it from C to java in java native interface(JNI)?

I have unsigned char buffer in which I have data and I need to copy it to a jbyteArray so that I could return it in byte array format. This is my piece of code C code:

JNIEXPORT jbyteArray JNICALL Java_hello1_recieve(JNIEnv *env, jobject object) 
{


      ssize_t bytes_read;
    /* receive the message */
    bytes_read = mq_receive(mq,buff, MAX_SIZE, NULL);
    jbyteArray b[bytes_read];
    CHECK(bytes_read >= 0);
    buff[bytes_read] = '\0';

    int i=0;
    while(buff[i]!='\0')
    {
        b[i]=buff[i];
        printf("%c\n",b[i]);
        i++;
    }


     /* cleanup */

     CHECK((mqd_t)-1 != mq_close(mq));
     CHECK((mqd_t)-1 != mq_unlink(QUEUE_NAME));
     return b;

}

here CHECK(x) is:

do{ 
    if (!(x)) 
    {
        fprintf(stderr, "%s:%d: ", __func__, __LINE__);
        perror(#x);
        exit(-1);
    }
  } while (0)

And the code for java side is:

public class hello1 {
public native void sayHello() ;
public native byte[] recieve() ;
public static void main (String args[]) {


    hello1 h = new hello1 () ;
    h.sayHello () ;
    System.out.println("connection open");
    byte[] rdata= new byte[3];
    rdata=h.recieve();
    int i=0;
    while( rdata[i] != '\0')
    {
      System.out.println( rdata [i]);
      i++;
    }
    System.out.println("connection closed");
    }
    static {
    System.loadLibrary ( "hello1" ) ;
 }
 }

but I am getting a java.lang.NullPointerException when I try to print rdata. Where is the problem? Thanks

Update this worked:-

 jbyteArray b=(*env)->NewByteArray(env, bytes_read);
 (*env)->SetByteArrayRegion(env, b, 0, bytes_read, (jbyte *)buff);
like image 637
Garima Virmani Avatar asked Nov 30 '16 06:11

Garima Virmani


1 Answers

 jbyteArray b=(*env)->NewByteArray(env, bytes_read);
 (*env)->SetByteArrayRegion(env, b, 0, bytes_read, (jbyte *)buff);   
// after cleanup
return b;
like image 151
timrau Avatar answered Nov 14 '22 22:11

timrau