Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

android - 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 :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...