Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

c - Why does write() not accept a pointer from a JNI ByteBuffer?

I'm writing a JNI function that takes a ByteBuffer as parameter and writes some of its content to a (special) file under Linux. The code looks like this:

/*
 * 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
",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;
}

If I try to run it, it gives me an "invalid argument" error (errno 22).

However, the following code runs without problems:

/*
 * 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;
}

I checked, the buffer address is not NULL (I checked with a java debugger: The pointer corresponds to the address member of my ByteBuffer instance) and the buffers capacity is way bigger then jLen

Why does the call to write() does not work with my buffer, when it works using a directly allocated string?

question from:https://stackoverflow.com/questions/66052695/why-does-write-not-accept-a-pointer-from-a-jni-bytebuffer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...