0

I have a relative large size std::string. And I want to pass it to Java without copying. And then pass back to another JNI lib. What is the best approach?

jlong some_jni_call() {
  string str = createLargeString(); // say this is from 3rd lib only returns string
  string* strInHeap = new string(str); // this should just increase the reference count?
  jlong handle = (long)strInHeap;
  return handle;
}

Then I can pass back to JNI:

void use_string(jlong handle) {
  string* str = (string*)handle;
  // use the str...
  delete str; // doesn't look so nice, since people can forget to delete
}

Is this a good approach?

earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63
counter
  • 1
  • 1
  • `string* strInHeap = new string(str)` creates a copy of `str`. std:.string is not reference-counted. – Stefan Zobel Sep 15 '16 at 13:16
  • It seems it is reference counted for certain cases: http://stackoverflow.com/questions/12520192/is-stdstring-refcounted-in-gcc-4-x-c11 – counter Sep 16 '16 at 06:59

1 Answers1

0

This is surely a feasible approach; you can even use similar trick to pass function pointers back and forth.

timrau
  • 22,578
  • 4
  • 51
  • 64