JNI:将字节从 C++ 传递到 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6246915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:00:01  来源:igfitidea点击:

JNI: passing bytes from c++ to java

javajava-native-interface

提问by justme_

HANDLE hFile = CreateFileA("C:\myfile.zip", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
const int size = GetFileSize(hFile, NULL);
char* buffer = new char[size];
DWORD read;
ReadFile(hFile, buffer, size, &read, NULL);

jclass cls = ...;
jmethodID id = ...;

jbyteArray arr = env->NewByteArray(size);
env->GetByteArrayRegion(arr, 0, size, (jbyte*) buffer);
env->CallStaticVoidMethod(cls, id, arr);

problem is that byte array contains just null bytes in java side, does anyone have idea why?

问题是字节数​​组在java端只包含空字节,有人知道为什么吗?

EDIT: oh my bad it should be SetByteArrayRegion, sorry! all working now :)

编辑:哦,我的错应该是 SetByteArrayRegion,对不起!现在都在工作:)

回答by Jason Rogers

I think your missing a line like :

我认为你错过了这样的一行:

(*env)-> SetByteArrayRegion(env, result, 0, size, fill);

check out :

查看 :

http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jnistring.html

http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jnistring.html

for more details

更多细节

also a similar question was answered here

也在这里回答了类似的问题

How to return an array from JNI to Java?

如何将数组从 JNI 返回到 Java?