Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Using the Ludii jar in cpp with JNI and calling the `listGames()` method
//compiled with g++ -g -I/usr/lib/jvm/java-8-openjdk-amd64/include -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/ ludii_jni_example.cpp -ljvm
#include <iostream>
#include <string.h>
#include <jni.h>
#include <stdlib.h>
using namespace std;
#define PATH_SEPARATOR ';'
#define USER_CLASSPATH "Ludii-0.3.0.jar"
#define GAME_LOADER "player/GameLoader"
JNIEnv *env;
JavaVM *jvm;
jint res;
void initJVM() {
#ifdef JNI_VERSION_1_2
JavaVMInitArgs vm_args;
JavaVMOption options[1];
options[0].optionString =
"-Djava.class.path=" USER_CLASSPATH;
vm_args.version = 0x00010002;
vm_args.options = options;
vm_args.nOptions = 1;
vm_args.ignoreUnrecognized = JNI_TRUE;
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
JDK1_1InitArgs vm_args;
char classpath[1024];
vm_args.version = 0x00010001;
/* Append USER_CLASSPATH to the default system class path */
sprintf(classpath, "%s%c%s",
vm_args.classpath = classpath;
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, &env, &vm_args);
#endif /* JNI_VERSION_1_2 */
void closeJVM() {
int main() {
//initialize the JVM
//Let's try to execute `final String[] games = GameLoader.listGames();` from the Ludii jar
//find the GameLoader class
jclass gameLoader = env->FindClass("player/GameLoader");
if(gameLoader == NULL)
cout << "Could not load class!" << endl;
return 1;
//find the listGames method
jmethodID mid = env->GetStaticMethodID(gameLoader,"listGames","()[Ljava/lang/String;");
if(mid == NULL)
cout << "Could not load method!" << endl;
return 1;
//execute the listGames method
jobjectArray stringArray = (jobjectArray) env->CallStaticObjectMethod(gameLoader,mid);
if(stringArray == NULL)
cout << "Could not load object!" << endl;
return 1;
//print the result of listGames
int stringCount = env->GetArrayLength(stringArray);
for (int i=0; i<stringCount; i++) {
//get array element and convert it from jstrng
jstring string = (jstring) (env->GetObjectArrayElement(stringArray, i));
const char *rawString = env->GetStringUTFChars(string, 0);
env->ReleaseStringUTFChars(string, rawString);
//destroy the JVM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.