我使用JNI调用c函数来创建接口。 我在android studio上收到以下错误消息
不兼容的类型
必需:java.io.FileDescriptor
发现:java.lang.Object
packet.java
FileDescriptor myDev= null;
myDev = JNI.prepare_fd("/dev/net/tun", myDev); =>this line hava above error
in2 = new FileInputStream(myDev);
JNI.java
public class JNI {
static {
System.loadLibrary("JNITest");
}
public static native Object prepare_fd(String filename, FileDescriptor fdobj);
}
packet_JNI.h
JNIEXPORT jobject JNICALL Java_com_example_packetcapture_JNI_prepare_fd (JNIEnv *, jclass, jstring );
JNITest.c
JNIEXPORT jobject JNICALL
Java_com_example_packetcapture_JNI_prepare_1fd(JNIEnv *env, jclass _ignore, jstring filename)
{
jfieldID field_fd;
jmethodID const_fdesc;
jclass class_fdesc, class_ioex;
jobject ret;
int fd;
char *fname;
class_ioex = (*env)->FindClass(env, "java/io/IOException");
if (class_ioex == NULL) return NULL;
class_fdesc = (*env)->FindClass(env, "java/io/FileDescriptor");
if (class_fdesc == NULL) return NULL;
fname = (*env)->GetStringUTFChars(env, filename, NULL);
fd = open(fname, O_RDWR | O_NONBLOCK);
(*env)->ReleaseStringUTFChars(env, filename, fname);
if (fd < 0) {
// open returned an error. Throw an IOException with the error string
char buf[1024];
sprintf(buf, "open: %s", strerror(errno));
(*env)->ThrowNew(env, class_ioex, buf);
return NULL;
}
// construct a new FileDescriptor
const_fdesc = (*env)->GetMethodID(env, class_fdesc, "<init>", "()V");
if (const_fdesc == NULL) return NULL;
ret = (*env)->NewObject(env, class_fdesc, const_fdesc);
// poke the "fd" field with the file descriptor
field_fd = (*env)->GetFieldID(env, class_fdesc, "fd", "I");
if (field_fd == NULL) return NULL;
(*env)->SetIntField(env, ret, field_fd, fd);
// and return it
return ret;
}
谁能给我一些想法?如何解决此错误。谢谢。
答案 0 :(得分:0)
以下行说明它是通用对象类型:
public static native Object prepare_fd(String filename, FileDescriptor fdobj);
最简单的修复方法是在设置myDev时将其强制转换为文件描述符:
myDev = (filedescriptor) JNI.prepare_fd("/dev/net/tun", myDev);