title: How to copy data from char buffer into jbyteArray and return it from C to java in java native interface(JNI)?
body: <p>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:</p>
  
  <pre><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 &gt;= 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;
  </code></pre>
  
  <p>}</p>
  
  <p>here CHECK(x) is:</p>
  
  <pre><code>do{ 
      if (!(x)) 
      {
          fprintf(stderr, "%s:%d: ", __func__, __LINE__);
          perror(#x);
          exit(-1);
      }
    } while (0)
  </code></pre>
  
  <p>And the code for java side is:</p>
  
  <pre><code>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" ) ;
   }
   }
  </code></pre>
  
  <p>but I am getting a java.lang.NullPointerException when I try to print rdata. Where is the problem? 
  Thanks</p>
  
  <p><strong><em>Update</em></strong>
  this worked:-</p>
  
  <pre><code> jbyteArray b=(*env)-&gt;NewByteArray(env, bytes_read);
   (*env)-&gt;SetByteArrayRegion(env, b, 0, bytes_read, (jbyte *)buff);
  </code></pre>