#include#include void callJavaMethod() { JavaVM* jvm; JNIEnv* env; JavaVMInitArgs vm_args; vm_args.version = JNI_VERSION_1_8; vm_args.nOptions = 0; vm_args.ignoreUnrecognized = JNI_FALSE; int res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); if (res < 0) { std::cout << "Error initializing JNI" << std::endl; return; } jclass mathClass = env->FindClass("java/lang/Math"); jmethodID randomMethod = env->GetStaticMethodID(mathClass, "random", "()D"); jdouble randomValue = env->CallStaticDoubleMethod(mathClass, randomMethod); std::cout << "Random number from Java: " << randomValue << std::endl; jvm->DetachCurrentThread(); } int main() { std::thread t(callJavaMethod); t.join(); std::cout << "Detached from Java VM" << std::endl; return 0; }
package mypackage; public class MyClass { static { System.loadLibrary("mylibrary"); } public static native void cppFunction(); public static void main(String[] args) { cppFunction(); System.out.println("Detached from Java VM"); } }In this example, we have a Java method called cppFunction() which is a native method implemented in C++. This method is called from the Java main() method, and afterwards we print a message indicating that we have detached from the JVM. In the C++ implementation, we can use cpp JavaVM DetachCurrentThread method to release the resources associated with the JVM. The package library used in these examples is the Java Native Interface (JNI).