Convert JNI -> jobject (basically map and/or map of map in java file) to std::map(c++)

Viewed 517

I have a native method in java file:-

class JNITest{
    public native void test(String param1, Map<String, Number> param2, Map<String, Map<String, Double>> param3)
}

After generating header file from java, map is converted to jobject in header file method:-

JNIEXPORT void JNICALL Java_com_jni_JNITest_test
(JNIEnv *env,
jobject self,
jstring param1,
jobject param2,
jobject param3) { }

I have a native method in cpp as:

int cpp_native(
std::string param1,
std::map<std::string, float>& param2,
std::map<std::string, std::map<std::string, float> >& param3) { }

Q:- I need to convert Jobject back to std::map(cpp) to pass it to cpp native method, could anyone please suggest standard approach for doing the same? Thanks in advance.

3 Answers

We have done a lot of work with C++/Java integration. The problem with passing complex data structures across the boundary is that you have to marshal the method invocations, which can be a really complex and error-prone endeavor. I've found it much easier to do something like this:

  • On the Java side, use gson or jackson to serialize your map to JSON
  • Pass the JSON string across the boundary
  • On the C++ side deserialize the JSON to a std::map

I'm not as familiar with the C++ side, but I see similar problems being addressed here

You can use scapix::link::java C++ JNI library to automatically convert between many C++ and Java types. Here is an example:

#include <scapix/java_api/java/lang/System.h>
#include <scapix/java_api/java/util/Locale.h>
#include <scapix/java_api/java/text/DateFormatSymbols.h>

using namespace scapix::link::java;
using namespace scapix::java_api;

void test1()
{
    // C++ objects are automatically converted to and from corresponding Java types.
    // This works for any type supported by scapix::link::java::convert() interface,
    // which supports many STL types and can be extended for your own types.

    std::string version = java::lang::System::getProperty("java.version");
    std::vector<std::string> languages = java::util::Locale::getISOLanguages();
    std::vector<std::vector<std::string>> zone_strings = java::text::DateFormatSymbols::getInstance()->getZoneStrings();
    std::map<std::string, std::string> properties = java::lang::System::getProperties();
}
Related