0

I want to create a C++ application that will call a function inside a running Java application. This is the code for my Java application:

package me.jumpak.testapp;

public class TestClass {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }

    public static void mymain() {   // <=== I want to call this function
        System.out.println("Hello, World in java from mymain");
    }
}

So I want the C++ application to somehow "inject" into the running JVM process and call the function mymain so it will execute the function and print the message (Hello, World in java from mymain). I know this is possible somehow but don't know how to do it. I have no idea where to start, or how to do this in C++ I've tried googling but haven't found anything yet.

1 Answers1

1

You always use JNI from c++ to create or attach to an existing jvm instance, and create objects or invoke methods ...

Something like ...

// Connect to an existing jvm
jint vm = JNI_GetCreatedJavaVMs(...

// Find the class
jclass cls = env->FindClass("your/namespace/Class");

// Get the method
jmethodID m = env->GetMethodID(clsm, "methodToInvoke", "()V");

// Call the method on the object
jobject res = env->CallObjectMethod(objInstance, m);

https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/invocation.html

jgoday
  • 2,768
  • 1
  • 18
  • 17
  • One more thing: what's jstr? – Mato Sustak Mar 21 '19 at 19:04
  • In this example you call a method on an instance of one object (you call the method m of the instance objInstance). If you want to call a static method use GetStaticMethodID and CallStatic*Method – jgoday Mar 21 '19 at 19:10