小编Mut*_* GM的帖子

JNI GetByteArrayElements () 错误

我是 JNI 的新手,所以我对 JNI 和英语都不熟悉。

我的JNI项目是一个简单的文件读写。在 Java 中读取文件并将字节数组传递给 C API,然后使用 C 将其写入文件。

我的源代码:

Java代码是:

public class FileIO {
   static {
      System.loadLibrary("FileIO");         
   }

   private native void writeFile(byte[] msg);

   public static void main(String[] args) throws IOException { 

      byte[] array = Files.readAllBytes(new File("PtFBWCTn.mp3").toPath());

      // System.out.println(array.length);
      new FileIO(). writeFile(array); 
   }
}
Run Code Online (Sandbox Code Playgroud)

C代码:

#include <jni.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "HelloJNI.h"

JNIEXPORT void JNICALL Java_FileIO_ writeFile (JNIEnv *env, jobject job, jbyteArray array ){

    jsize num_bytes = (*env)->GetArrayLength(env, array);
    printf("Byte length : %d\n" , …
Run Code Online (Sandbox Code Playgroud)

c java java-native-interface c-strings

6
推荐指数
1
解决办法
8412
查看次数

如何在JNI中将Java字节数组的内容转换为C字符串?


更新:

错误:jbyte* elements = (*env)->GetByteArrayElements(env, array, NULL);仅返回 8 个字节。提供以 jbytearray 形式检索字节的任何替代方法。


我是 JNI 的新手,所以我对 JNI 和英语都不熟悉。

现在我尝试使用 Java 读取文件的简单 JNI 程序,并使用 C 将其写入文件。

文件读取java代码:

public class FileIO {
   static {
      System.loadLibrary("io");         
   }

   private native void writeToFile(byte[] msg);

   public static void main(String[] args) throws IOException { 
      FileInputStream fileInputStream=null;

      File file = new File("version1-1.png");

      byte[] bFile = new byte[(int) file.length()];

      try {
         //convert file into array of bytes
         fileInputStream = new FileInputStream(file);
         fileInputStream.read(bFile);
         fileInputStream.close();
         System.out.println("Done");

      } catch(Exception e){
         e.printStackTrace();
      } …
Run Code Online (Sandbox Code Playgroud)

c java java-native-interface

5
推荐指数
1
解决办法
7834
查看次数

标签 统计

c ×2

java ×2

java-native-interface ×2

c-strings ×1