Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 views
in Technique[技术] by (71.8m points)

java - convert c++ map to jobject JNI?

I want to transfer a C++ map to Java and have no idea how to define the return parameter so the method works. I had no trouble with string or int as return parameters, but i can′t get map working.
My Java method looks like this:

private native Map<String,String> sayHello();

My C++ Code is:

#include <stdio.h>
#include "stdafx.h"
#include "jni.h"
#include "HelloJNI.h"
#include <utility>
#include <map>
#include <string.h>
#include <iostream>

using namespace std;

JNIEXPORT jobject JNICALL Java_HelloJNI_sayHello
(JNIEnv *, jobject)
{
    map<string, string> mMap;
    mMap["1"] = "Ladi";
    mMap["2"] = "Dida";
    return mMap;
}

And of course i get an error, telling me i have to convert mMap to jobject somehow. But i have no idea how to do this.

I hope its no double-post, i just found some questions dealing with transmitting lists.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use jni api to find HashMap java class, then its methods for construction and insertion of elements. Then Add all the elements and finally return this map. It should look as follows (warning - pseudocode !!!)

env->PushLocalFrame(256); // fix for local references

jclass hashMapClass= env->FindClass(env, "java/util/HashMap");
jmethodID hashMapInit = env->GetMethodID(env, hashMapClass, "<init>", "(I)V");
jobject hashMapObj = env->NewObject(env, hashMapClass, hashMapInit, mMap.size());
jmethodID hashMapOut = env->GetMethodID(env, hashMapClass, "put",
            "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");

for (auto it : mMap)
{
    env->CallObjectMethod(env, hashMap, put,
         env->NewStringUTF(it->first.c_str()),
         env->NewStringUTF(it->second.c_str()));
}

env->PopLocalFrame(hashMap);

return hashMap;

ps. I usually code jni under android, but above code should work the same under other platforms.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...