C++ Call a function inside a running JVM

╄→尐↘猪︶ㄣ 提交于 2021-02-08 09:46:19

问题


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:


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



来源:https://stackoverflow.com/questions/55286883/c-call-a-function-inside-a-running-jvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!