为什么 write() 不接受来自 JNI 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,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() 的调用不起作用?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...