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
JNI: passing bytes from c++ to java
提问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
也在这里回答了类似的问题