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);
jbyteArray b=(*env)->NewByteArray(env, bytes_read);
(*env)->SetByteArrayRegion(env, b, 0, bytes_read, (jbyte *)buff);
// after cleanup
return b;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With