简体   繁体   English

如何在jni中将jbyteArray转换为本机char *?

[英]How to convert jbyteArray to native char* in jni?

I am trying to convert a jbyteArray to native c string (char*) in jni? 我想在jni中将jbyteArray转换为本机c字符串(char *)? Unfortunately I can't find any documentation on how to do that. 不幸的是我找不到任何关于如何做到这一点的文档。 I'm invoking a java function with the following prototype in the c code. 我正在使用c代码中的以下原型调用java函数。

public static byte[] processFile(byte[] p_fileContent)

In the c code I am invoking this function which is returning a byte array. 在c代码中,我正在调用此函数,该函数返回一个字节数组。 The content of this byte array is a java string. 该字节数组的内容是一个java字符串。 But I need to convert it to ac string. 但我需要将其转换为ac字符串。

jbyteArray arr = (jbyteArray) env->CallObjectMethod(clsH, midMain, jb);
printf("%s\n", (char*) arr);

I believe you would use GetByteArrayElements and ReleaseByteArrayElements . 我相信你会使用GetByteArrayElementsReleaseByteArrayElements Something like: 就像是:

boolean isCopy;
jbyte* b = GetByteArrayElements(env, arr, &isCopy);

You should be able to cast b to char* at this point in order to access the data in the array. 此时,您应该能够将bchar* ,以便访问数组中的数据。 Note that this may create a copy of the data, so you'll want to make sure to release the memory using ReleaseByteArrayElements : 请注意,这可能会创建数据的副本,因此您需要确保使用ReleaseByteArrayElements释放内存:

ReleaseByteArrayElements(env, arr, b, 0);

The last parameter is a mode indicating how changes to b should be handled. 最后一个参数是一个模式,指示应如何处理对b更改。 0 indicates that the values are copied back to arr . 0表示将值复制回arr If you don't want to copy the data back to arr , use JNI_ABORT instead. 如果您不想将数据复制回arr ,请改用JNI_ABORT

For more details see the JNI Reference . 有关更多详细信息,请参阅JNI参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM