Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A correct way to convert byte[] in java to unsigned char* in C++, and vice versa?

I'm newbie in C++ and JNI, I try to find a correct way to convert byte[] in java to unsigned char* in C++ by using JNI, and vice versa ! (I'm working on android) After looking for a solution in google and SO, I haven't found a good details way to convert byte[] in java to C++. Please help me, and provide a solution for a vice versa (unsigned char* in C++ to byte[] in java). Thanks very much

  • byte[] in java to unsigned char* in C++:

JAVA :

private static native void nativeReceiveDataFromServer(byte[] value, int length); 

JNI:

... (JNIEnv* env, jobject thiz, jbyteArray array, jint array_length) {     ??? } 

PS: I modified my question for being a real question for my problem :(

like image 631
Hien Nguyen Avatar asked May 21 '13 09:05

Hien Nguyen


People also ask

Can we convert byte to char in Java?

First, the byte is converted to an int via widening primitive conversion (§5.1. 2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1. 3).

How do you turn a char into a byte?

Syntax: byte by = (byte) ch; Here, ch is the char variable to be converted into Byte. It tells the compiler to convert the char into its byte equivalent value.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.


1 Answers

You can use this to convert unsigned char array into a jbyteArray

jbyteArray as_byte_array(unsigned char* buf, int len) {     jbyteArray array = env->NewByteArray (len);     env->SetByteArrayRegion (array, 0, len, reinterpret_cast<jbyte*>(buf));     return array; } 

to convert the other way around...

unsigned char* as_unsigned_char_array(jbyteArray array) {     int len = env->GetArrayLength (array);     unsigned char* buf = new unsigned char[len];     env->GetByteArrayRegion (array, 0, len, reinterpret_cast<jbyte*>(buf));     return buf; } 
like image 186
Zharf Avatar answered Sep 19 '22 23:09

Zharf