Skip to content

Instantly share code, notes, and snippets.

@MasseGuillaume
Created April 26, 2012 15:51
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MasseGuillaume/2500529 to your computer and use it in GitHub Desktop.
Save MasseGuillaume/2500529 to your computer and use it in GitHub Desktop.
Insert key value pair in a std::map then output in a java HashMap
// @author Guillaume Masse
#include "JHashMap.h"
#include <string>
using namespace std;
void JHashMap::insert( std::string key, std::string value )
{
map.insert( pair<string,string>( key, value ) );
}
jobject JHashMap::toJObject( JNIEnv* env, jclass )
{
jclass clazz = env->FindClass("java/util/HashMap");
jmethodID init = env->GetMethodID(clazz, "<init>", "()V");
jobject propertyMap = env->NewObject(clazz, init);
jmethodID putMethod = env->GetMethodID(
clazz,
"put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"
);
for( auto it = map.begin(); it != map.end(); ++it )
{
jstring key = (*env).NewStringUTF( (*it).first.c_str() );
jstring value = (*env).NewStringUTF( (*it).second.c_str() );
(*env).CallVoidMethod(
propertyMap,
putMethod,
key,
value
);
}
return propertyMap;
}
#pragma once
// @author Guillaume Masse
#include <map>
#include <string>
#include "jni.h"
class JHashMap
{
public:
void insert( std::string key, std::string value );
jobject toJObject(JNIEnv *, jclass);
private:
std::map< std::string, std::string > map;
};
@hzxie
Copy link

hzxie commented May 30, 2015

Why doesn't it work for me? I got an segment fault while calling CallVoidMethod.

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00000000700bb2cd, pid=8040, tid=2920
#
# JRE version: Java(TM) SE Runtime Environment (8.0_05-b13) (build 1.8.0_05-b13)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.5-b02 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# V  [jvm.dll+0x13b2cd]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# D:/Development/Java/voj/judger/hs_err_pid8040.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.sun.com/bugreport/crash.jsp
#

@ZhangQian-Cheryl
Copy link

when call map "put" method, should use "env->CallObjectMethod", not "CallVoidMethod".
it's works. thk

@piotrros
Copy link

Can someone tell me how to call toJObject function and what should I give as "jclass" parameter? I'm clueless.

@piotrros
Copy link

Ok, figured it out. Just removed jclass parameter :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment