c++ 调用 java
编译环境 linux Ubuntu13.10
JDK 信息
[email protected]:/usr/java# echo $JAVA_HOME
/usr/java/jdk1.7.0_65
[email protected]:/usr/java# echo $CLASSPATH
.:/usr/java/jdk1.7.0_65/lib:/usr/java/jdk1.7.0_65/jre/lib:
[email protected]:/# echo $JAR_HOME
/usr/java/jdk1.7.0_65/jre
[email protected]:/# echo $PATH
/usr/java/jdk1.7.0_65/bin:/usr/java/jdk1.7.0_65/jre/bin
[code=c]
在home目录下建议个com目录,然后再在com目录下建一个test目录
[code=c]
[email protected]:/home/com/test# pwd
/home/com/test
编写一个java程序
[email protected]:/home/com/test# cat MyAdd.java
package com.test;
public class MyAdd.j{
public static int add(int a, int b)
{
return a+b;
}
}
[email protected]:/home/com/test# javac MyAdd.java
[email protected]:/home/com/test# ls
MyAdd.class MyAdd.java
这里需要用javah生成 MyAdd.h文件吗?
然后写一个test.cpp 文件
#include <jni.h>
#include <stdio.h>
int main()
{
JavaVM * jvm = (JavaVM *)0;
JNIEnv * env = (JNIEnv *)0;
JavaVMInitArgs vm_args;
long status;
jclass cls;
jmethodID mid;
jint square;
jboolean jnot;
jobject jobj;
vm_args.version = JNI_VERSION_1_6;
vm_args.options = (JavaVMOption *)0;
vm_args.ignoreUnrecognized = JNI_FALSE;
status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if(status != JNI_ERR)
{
cls = env->FindClass("com/test/MyAdd");
if(cls != 0)
{
printf("find java class success\n");
mid = env->GetMethodID(cls, "<init>", "(V)");
if(mid != 0)
{
jobj = env->NewObject(cls, mid);
printf("init ok!\n");
}
// 调用add函数
mid = env->GetStaticMethodID(cls, "add", "(II)I");
if(mid != 0)
{
square = env->CallStaticIntMethod(cls, mid, 5, 5);
printf("square :%d\n", square);
}
}
else
{
fprintf(stderr, "FindClass failed!\n");
}
jvm->DestroyJavaVM();
fprintf(stdout, "Java VM destry!\n");
return 0;
}
else
{
printf("create java jvm fail\n");
return -1;
}
}
编译
[email protected]:/home/com/test# cat make.sh
g++ -o test \
-I/usr/java/jdk1.7.0_65/include \
-I/usr/java/jdk1.7.0_65/include/linux \
-L/usr/bin/java \
-L/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/amd64/serve test.cpp -ljvm
[email protected]:/home/com/test# ls
MyAdd.class MyAdd.java make.sh test test.cpp
[email protected]:/home/com/test# ./test
FindClass failed!
Java VM destry!