yerzhan7
yerzhan7

Reputation: 305

Passing NewDirectByteBuffer from C++ to Java (JNI)

I have this C++ code:

char *buffer = new char[100];

/*
*  ...populate this char array with some data...
*/

jobject jbuffer = env->NewDirectByteBuffer(buffer, 100);

Afterwards, I want to pass this DirectByteBuffer that I have created in C++ to Java.

I have 2 questions:

  1. Will env->NewDirectByteBuffer(buffer, 100) clear out my data in char array buffer? Is this the correct way of doing this?
  2. When will this buffer be deleted? Should I delete it in C++ sometime afterwards or will Java's GC handle it for me?

Upvotes: 0

Views: 1945

Answers (1)

Alex Cohn
Alex Cohn

Reputation: 57173

jobject jbuffer = env->NewDirectByteBuffer(buffer, 100);

creates a local reference to the Java object. It will be marked unused when explicitly released, or if you use PushLocalFrame()/PopLocalFrame(), or when the JNI function that allocated this local reference, returns.

After that, the GC will decide to delete the buffer following the same rules as for regular Java objects.

Upvotes: 2

Related Questions