C++调用JVM执行

原创文章,转载请注明: 转载自慢慢的回味

本文链接地址: C++调用JVM执行

这是一个从C++调用JVM的使用例子

JavaCPPJNI工程 JavaCPPTest工程

运行时需要加入环境变量LD_LIBRARY_PATH=/root/openjdk/build/linux-amd64/j2sdk-image/jre/lib/amd64/server

//============================================================================
// Name        : JavaCPPJNI.cpp
// Author      : 
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
 
#include <iostream>
#include "jniLegacyLibrary.h"
using namespace std;
 
int main() {
	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
 
	JavaVM* myvm = JavaCPP_init(0, 0);
	if(myvm == NULL){
		return -1;
	}
	jint version = JNI_OnLoad(myvm, 0);
	JNIEnv* myenv;
	myvm->GetEnv((void**) &myenv, JNI_VERSION_1_6);
	jclass cls = myenv->FindClass("com/telenav/LegacyLibrary$LegacyClass");
	jmethodID cid = myenv->GetMethodID(cls, "<init>", "()V");
	if (cid == NULL) {
		return -1; /* exception thrown */
	}
	/* Construct a java.lang.String object */
	jobject obj = myenv->NewObject(cls, cid);
	if (obj == NULL) {
		return -1; /* exception thrown */
	}
	jmethodID mid =
			myenv->GetMethodID(cls, "sayHello", "(Ljava/lang/String;)V");
	jstring pname = myenv->NewStringUTF("Derek\n");
	myenv->CallVoidMethod(obj, mid, pname);
	Java_com_telenav_LegacyLibrary_00024LegacyClass_sayHello(myenv,obj,pname);
	return 0;
}

本作品采用知识共享署名 4.0 国际许可协议进行许可。

发表回复