Search code examples
javac++code-injection

C++ Call a function inside a running JVM


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.


Solution

  • 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