C ++在正在运行的JVM中调用函数 [英] C++ Call a function inside a running JVM

查看:92
本文介绍了C ++在正在运行的JVM中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个C ++应用程序,该应用程序将在正在运行的 Java应用程序中调用一个函数.这是我的Java应用程序的代码:

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");
    }
}

所以我希望C ++应用程序以某种方式注入"到正在运行的JVM进程中并调用函数 mymain ,以便它将执行该函数并打印消息(Hello,来自mymain的Java中的World).我知道这是有可能的,但不知道该怎么做.我不知道从哪里开始,或者如何在C ++中做到这一点,我已经尝试使用Google搜索,但是还没有发现任何东西.

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.

推荐答案

您始终使用c ++中的JNI来创建或附加到现有的jvm实例,并创建对象或调用方法...

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

类似...

// 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

这篇关于C ++在正在运行的JVM中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆