|
今天看阿里巴巴搜索技术中心文档,无意发现:
“camera内部是采用java语言来实现的,本接口把camera的java接口封装成C++接口,通过c语言构建jvm来调用camera的java接口”,
我就很想一看究竟c++如何调用java程序了。
参考http://www.velocityreviews.com/f ... ll-java-from-c.html
D:\lr_script\MyJNI>java -version
java version "1.5.0_06"
DemoMain.java内容如:
import java.io.*;
public class DemoMain {
public static void main(String[] args) throws java.io.IOException, java.lang.NullPointerException
{
System.out.println("This is a test.");
}// end main().
}// end class DemoMain.
采用vc6++ IDE,采用JNI技术实现。
(1) 编译时:
C++ preprocessor->additional include directories:
加入 D:\Sun\AppServer\jdk\include
(2)运行时,
把 D:\Sun\AppServer\jdk\jre\bin\server\jvm.dll 加入环境变量。
#ifndef __cplusplus
#define __cplusplus
#endif
#include "jni.h"
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#pragma comment (lib,"D:\\Sun\\AppServer\\jdk\\lib\\jvm.lib")
void main() {
JavaVM *jvm;
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options[3];
options[0].optionString = "-Djava.compiler=NONE";
options[1].optionString = "-Djava.classpath=.";
options[2].optionString = "-verbose:jni";
vm_args.version = JNI_VERSION_1_4;
vm_args.nOptions = 3;
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_TRUE;
jint res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if (res < 0) {
fprintf(stderr, "Can't create Java VM\n");
exit(1);
};
jclass cls = env->FindClass("DemoMain");
if (cls == 0) printf("Sorry, I can't find the class");
fprintf(stdout, "This is invokeSimplified4.\n");
jmethodID get_main_id;
if(cls != NULL)
{
get_main_id =env->GetStaticMethodID(cls,"main","([Ljava/lang/String;)V");
fprintf(stdout, "This is invokeSimplified5.\n");
if(get_main_id != NULL )
{
jclass string = env->FindClass("java/lang/String");
jobjectArray args = env->NewObjectArray(0,string, NULL);
fprintf(stdout, "This is invokeSimplified6.\n");
int i = env->CallIntMethod(cls, get_main_id, args);
fprintf(stdout, i+ "This is invokeSimplified7.\n");
}
}// end IF.
jvm->DestroyJavaVM();
fprintf(stdout, "Java VM destory\n");
}//end main. |
|