简体   繁体   中英

Android JNI: pass std::string to Java and back to C++

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM