在c++中,将java中的字节转换为无符号的char*的正确方法,反之亦然?

时间:2021-03-01 22:29:51

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

在c++和JNI中,我是新手,我试图找到一种正确的方法,将java中的byte[]转换为使用JNI的无符号char*,反之亦然!(我正在开发android)在谷歌中寻找解决方案之后,我还没有找到一个很好的方法来将java的字节转换成c++。请帮助我,并提供一个解决方案,反之亦然(在c++中无符号的char*,在java中是字节[])。非常感谢

  • byte[] in java to unsigned char* in C++:
  • 字节[]在java中无符号char*在c++中:

JAVA :

JAVA:

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

JNI:

JNI:

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

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

PS:我修改了我的问题,因为我的问题是一个真正的问题:

1 个解决方案

#1


53  

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

可以使用它将未签名的char数组转换为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;
}

#1


53  

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

可以使用它将未签名的char数组转换为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;
}