0

I have a very larger JSON(hundreds of KB) and plan to pass it to C++ through JNI. I wonder if this a proper way to do it.

My concern is:

  1. Although string in JAVA is in heap, but will it cause my C++ stack overflow during JNI copying from JVM to C++?

  2. Will JNI become a bottle neck? How fast is the JNI?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Michael
  • 1,313
  • 11
  • 25
  • Please provide a reason to close. What you want me to do? – Michael Feb 20 '21 at 10:46
  • 1
    You're passing a reference to the string, not a copy of the actual string data. Then, if you decide to make a copy of the string data in your native code, it's up to you where to put the copied data. – Michael Feb 20 '21 at 11:04
  • @Michael Thanks for your comments. You mean JNI actually pass a JAVA string by reference to native(jstring)? – Michael Feb 20 '21 at 11:38
  • 1. No risk of stack overflow if you use `std::string` or similar. You certainly don't want to allocate a buffer on stack to copy the string, that would be dangerous and useless. 2. Difficult to be sure without profiling, but copying strings should be very fast. Serializing and parsing JSON may be a bottleneck, though. – prapin Feb 20 '21 at 11:56
  • If I remember correctly, Java strings passed to JNI uses a modified version of UTF-16. To store into a `std::string`, some code is needed to convert that pseudo-UTF-16 into UTF-8. And even if using `std::wstring`, you might need some code to convert pseudo-UTF-16 into real UTF-16 or UTF-32. – prapin Feb 20 '21 at 12:01
  • @prapin Thanks so much for your comments. I am still kind of confused. Since for JNI function, it will take a JAVA string as the type of jstring, and later can be converted to std::string inside JNI function, but wouldn't this input parameter consume large stack? Since its not passing by reference I think. – Michael Feb 20 '21 at 13:24
  • 1
    A `jstring` is a kind of `jobject`, which in turn holds (or points to) a reference to the actual object. I don't know what you are reading that is telling you otherwise. – Michael Feb 20 '21 at 15:08
  • See https://stackoverflow.com/q/41820039 for how to convert a `jstring` to a valid UTF-8 `std::string` (in case this is what you want). None of the implementation code in answers would cause a stack overflow even with huge strings. – prapin Feb 20 '21 at 16:30
  • @Michael Thanks. I think you already have an answer to the question, would you mind putting your comments as an answer? Or I will answer and close if you don't mind. – Michael Feb 22 '21 at 02:09
  • Take a look here: https://github.com/mkowsiak/jnicookbook/blob/master/recipes/recipeNo040/c/recipeNo040_PassByteBuffer.c - maybe this is something you are looking for. – Oo.oO Feb 22 '21 at 18:00
  • 1
    Thanks for the book recommendation! @Oo.oO – Michael Feb 23 '21 at 01:57

0 Answers0