c++ 调用 java
编译环境 linux Ubuntu13.10
JDK 信息
编写一个java程序
这里需要用javah生成 MyAdd.h文件吗?
然后写一个test.cpp 文件
编译
没有找到那个类?求指定。。。。
编译环境 linux Ubuntu13.10
JDK 信息
root@master:/usr/java# echo $JAVA_HOME
/usr/java/jdk1.7.0_65
root@master:/usr/java# echo $CLASSPATH
.:/usr/java/jdk1.7.0_65/lib:/usr/java/jdk1.7.0_65/jre/lib:
root@master:/# echo $JAR_HOME
/usr/java/jdk1.7.0_65/jre
root@master:/# 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]
root@master:/home/com/test# pwd
/home/com/test
编写一个java程序
root@master:/home/com/test# cat MyAdd.java
package com.test;
public class MyAdd.j{
public static int add(int a, int b)
{
return a+b;
}
}
root@master:/home/com/test# javac MyAdd.java
root@master:/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;
}
}
编译
root@master:/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
root@master:/home/com/test# ls
MyAdd.class MyAdd.java make.sh test test.cpp
root@master:/home/com/test# ./test
FindClass failed!
Java VM destry!
没有找到那个类?求指定。。。。