JAVA调用C++ dll C++调用JAVA的例子

2008-08-29 11:29

from:http://hi.baidu.com/spmno/blog/item/52ca772ca95213ec8a1399cc.html


首先是JAVA的一个程序,test.java
public class test{
static {
    try{System.loadLibrary("test");}
    catch(UnsatisfiedLinkError e){}
}
public native void ss();
public static void uu();{System.out.println("I'm uu");}
public static void main(String[] arg){
    new test();
}
public test(){
    ss();
}
}
之后用javah的方法生成头文件test.h。
再写C++文件--nn.cpp
#include <iostream>
#include <jni.h>
#include "test.h"
using std::cout;
using std::endl;
JNIEXPORT void JNICALL Java_test_ss(JNIEnv *env,jobject obj){
cout<<"let us begin"<<endl;
jclass jcl=env->FindClass("test");
if(env->ExceptionCheck()==JNI_TRUE|jcl==NULL){
    cout<<"load error"<<std::endl;
}
jmethodID mid=env->GetStaticMethodID(jcl,"uu","()V");
if(env->ExceptionCheck()==JNI_TRUE|mid==NULL){
    cout<<"Can't find the method"<<endl;
}
env->CallStaticObjectMethod(jcl,mid);
}
将其编译后生成库文件,LINUX为libtest.so,WINDOWS下为*.dll。本人是在LINUX做的实验,已成功,输出结果为
let us begin
i am uu
在此十分感谢武汉的dijk(the day after yesterday)的文章。没有这篇文章我不可能在这么短的时间内完成这个程序。
如有不明白请留言,我会在最短的时间内给出答案。

你可能感兴趣的:(java,C++,linux,jni,null,dll)