为什么 write() 不接受来自 JNI ByteBuffer 的指针?

时间:2021-02-04 19:39:56

标签: c java-native-interface bytebuffer

我正在编写一个 JNI 函数,它将一个 ByteBuffer 作为参数并将其一些内容写入 Linux 下的(特殊)文件。代码如下所示:

/*
 * Class:     myPackage_myClass
 * Method:    writeByteBuffer
 * Signature: (Ljava/nio/ByteBuffer;I)I
 */
JNIEXPORT jint JNICALL Java_myPackage_myClass_writeByteBuffer
  (JNIEnv *env, jobject thiz, jobject jBuffer, jint jLen)
{
  /* getting my file descriptor (fd) */
  const void* pointer = (void *) (*env)->GetDirectBufferAddress(env,(jobject)jBuffer);
  fprintf(stderr,"Address %p\n",pointer); //gives for example : "Address 0x7f58ac680640"
  int res = (int) write(fd, pointer,jLen);
  if(res < jLen) {
    throwErrnoExceptionError(env);
    return cleanup_running(ERR_NR);
  }
  return OK;
}

如果我尝试运行它,它会给我一个“无效参数”错误(errno 22)。

但是,以下代码运行没有问题:

/*
 * Class:     myPackage_myClass
 * Method:    writeByteBuffer
 * Signature: (Ljava/nio/ByteBuffer;I)I
 */
JNIEXPORT jint JNICALL Java_myPackage_myClass_writeByteBuffer
  (JNIEnv *env, jobject thiz, jobject jBuffer, jint jLen)
{
/* getting my file descriptor (fd) */
  char test[] = "Just some random text to test";
  int res = (int) write(fd, test,jLen);
  if(res < jLen) {
    throwErrnoExceptionError(env);
    return cleanup_running(ERR_NR);
  }
  return OK;
}

我检查过,缓冲区地址不是NULL(我用java调试器检查过:指针对应于我的address实例的ByteBuffer成员)并且缓冲区容量是比 jLen 大

当我的缓冲区使用直接分配的字符串时,为什么对 write() 的调用不起作用?

0 个答案:

没有答案