3

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.

  • You could try to access the std::map from Java using, for example, JavaCPP: https://github.com/bytedeco/javacpp Let me know if you're interested, I could provide some example code as an answer. – Samuel Audet Jan 24 '19 at 08:59

3 Answers3

4

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

Wheezil
  • 3,157
  • 1
  • 23
  • 36
1

It will require a little bit of struggle. Take a look here:

http://jnicookbook.owsiak.org/recipe-No-020/

also, take a look here for samples related to passing Map into native code

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo037 https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo038

Oo.oO
  • 12,464
  • 3
  • 23
  • 45
0

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();
}
Boris Rasin
  • 448
  • 4
  • 12