简体   繁体   English

C ++在正在运行的JVM内调用函数

[英]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. 我想创建一个C ++应用程序,它将在运行的 Java应用程序中调用一个函数。 This is the code for my Java application: 这是我的Java应用程序的代码:

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). 因此,我希望C ++应用程序以某种方式“注入”正在运行的JVM进程并调用函数mymain以便它将执行该函数并打印消息(Hello,来自mymain的Java中的World)。 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. 我不知道从哪里开始,或者如何在C ++中做到这一点,我已经尝试使用谷歌搜索,但是还没有发现任何东西。

You always use JNI from c++ to create or attach to an existing jvm instance, and create objects or invoke methods ... 您总是使用c ++中的JNI来创建或附加到现有的jvm实例,并创建对象或调用方法...

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://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/invocation.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM