我试图在Java中使用O_direct
而不是Linux中的JNI。
这是java部分:
public class jnitest {
static {
System.loadLibrary("jnitest"); // Load native library at runtime
// hello.dll (Windows) or libhello.so (Unixes)
}
private native void test();
private native void write(String path, byte[] chunkpayload);
public static void main(String[] args) {
try{
jnitest t=new jnitest();
byte[] chunk=new byte[5];
chunk[0]=1;
chunk[1]=2;
chunk[2]=3;
chunk[3]=4;
chunk[4]=5;
String s="outtest";
t.write(s,chunk);
}catch(Exception e){
System.out.println("fehler lol");
}
}
}
这是C部分:
#define _GNU_SOURCE
#include <jni.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include "jnitest.h"
#define BLOCKSIZE 512
JNIEXPORT void JNICALL Java_jnitest_write(JNIEnv *env, jobject obj, jstring jpath, jbyteArray jchunkpayload){
const char *path=(*env)->GetStringUTFChars(env, jpath, 0);
printf("path=%s \n",path);
(*env)->ReleaseStringUTFChars(env, jpath, path);
int len = (*env)->GetArrayLength (env,jchunkpayload);
printf("lenght= %d \n",len);
unsigned char* payload =(*env)->GetByteArrayElements(env,jchunkpayload,0);
int i=0;
for(i=0;i<len-1;i++){
printf("%02x \n",(int)payload[i]);
}
void *buffer;
int fd = open(path, O_SYNC|O_APPEND|O_CREAT|O_DIRECT);
posix_memalign(&buffer,BLOCKSIZE,BLOCKSIZE);
memcpy(buffer,payload,len);
write(fd,buffer,BLOCKSIZE);
printf("writen to file\n");
(*env)->ReleaseByteArrayElements(env,jchunkpayload,payload,JNI_ABORT);
free(buffer);
return;
}
JNIEXPORT void JNICALL Java_jnitest_test(JNIEnv *env, jobject obj){
printf("test\n");
return;
}
程序不会失败,但数据永远不会被写入。我知道我可以使用JNA,但我想使用JNI。有人有一个使用O_direct
在JNI上用java编写字节数组的工作示例吗?