您需要jbyte*
从中获取 a jbytearray
,这是一个 Java 对象:
public class Sample {
public static final native void write(byte[] byteArray);
}
#include <jni.h>
#include <fstream>
extern "C" JNIEXPORT void JNICALL Java_Sample_write(JNIEnv *env,
jclass,
jbyteArray jba) {
jbyte *arr = env->GetByteArrayElements(jba, nullptr);
if (!arr) {
return;
}
jint len = env->GetArrayLength(jba);
std::ofstream("myfile.bin", std::ios::binary)
.write(reinterpret_cast<char *>(arr), len);
env->ReleaseByteArrayElements(jba, arr, JNI_ABORT);
}
您可以使用以下方法进行测试:
project(sample_jni)
cmake_minimum_required(VERSION 2.8.8)
include(FindJNI)
if (JNI_FOUND)
message(STATUS "JNI_INCLUDE_DIRS=${JNI_INCLUDE_DIRS}")
message(STATUS "JAVA_JVM_LIBRARY=${JAVA_JVM_LIBRARY}")
else()
message(FATAL_ERROR "Found JNI: failed")
endif()
if(MSVC)
add_definitions(-D_CRT_SECURE_NO_WARNINGS=1 -Dstrdup=_strdup -Dputenv=_putenv)
endif()
if(NOT(MSVC))
add_compile_options(-Wall -Wno-padded -Wno-unknown-pragmas -Wno-switch -Werror)
endif()
set(SOURCE_FILES
jni.cpp)
add_library(sample_jni SHARED ${SOURCE_FILES})
set_target_properties(sample_jni PROPERTIES
C_VISIBILITY_PRESET hidden)
target_include_directories(sample_jni PRIVATE ${JNI_INCLUDE_DIRS})
import java.nio.charset.Charset;
public class Main {
public static void main(String[] args) {
System.loadLibrary("sample_jni");
byte[] bytes = args[0].getBytes(Charset.forName("UTF-8"));
Sample.write(bytes);
}
}
编译 Java 类和本机库后:
$ java -Djava.library.path=$(pwd) -cp . Main foobar
$ cat myfile.bin
foobar